javascript - 为什么我的助手集合查询没有反射(reflect)在 html 模板中?

标签 javascript events meteor helper meteor-publications

按照关于如何“Write an API”的教程,我似乎被卡住了,无法超越如何让生成的 API key 显示在模板中。

我在助手中有一个查询 APIKeys.find().fetch() 应该正确反射(reflect)在 html 模板中,但它没有。我花了几个小时查看我的代码,但没有注意到代码中的任何错误。

我对 Meteor 并不陌生,这让它变得更加烦人!

请帮忙!

在下面找到模板代码: /client/main.html

<template name="apiKey">
<div class="row">
  <div class="col-xs-12 col-sm-6">
  <h4 class="page-header">Your API Key</h4>
  <p>To gain access to the Pizza API, use the following API Key. 
     Make sure to keep it super safe! <strong>If you'd like to
     generate a new key, click the "refresh" icon on the field
     below</strong>.</p>

  <label class="sr-only" for="apiKey">Your API Key</label>
    <div class="input-group">
    <input type="text" readonly class="form-control" id="apiKey" placeholder="API Key" value="{{apiKey}}">
    <div class="input-group-addon regenerate-api-key"><span class="glyphicon glyphicon-refresh"></span></div>
  </div>
</div>

在上面的模板中,value="{{apiKey}}" 下的模板中没有呈现任何内容。我不明白这是为什么。

在下面找到我的助手代码:/client/main.js

import '../imports/api/tasks.js';

Template.apiKey.helpers({
apiKey: function() {
        var apiKey = APIKeys.findOne();

        if ( apiKey ) {
            return apiKey.key;
            console.log("Sucessful");
        }
        else {
            console.log("Failed! Can't find: APIKeys.findOne()");    
        }
     }

});

上面的帮助程序代码在控制台中呈现:失败!找不到:APIKeys.findOne()。 此外,当我在控制台中查询 APIKeys.find().fetch() 时,我得到了这个:

[]

在下面找到我的 onCreated 代码:/client/main.js

Template.apiKey.onCreated(function(){
  console.log("Your in onCreated!");
  this.subscribe( "APIKey" );
});

上面的 onCreated 代码在控制台中呈现:Your in onCreated!

在下面找到触发生成新 API key 的事件代码:/client/main.js

import '../imports/api/tasks.js';

Template.apiKey.events({
'click .regenerate-api-key': function( ){
        var userId = Meteor.userId();
        confirmRegeneration = confirm( "Are you sure? This will 
        invalidate your current key!" );

       if ( confirmRegeneration ) {
          Meteor.call( "regenerateApiKey", userId, function( error, response ) {
       if ( error ) {
          alert( error.reason, "danger" );
       }
       else {
           alert( "All done! You have a new API key: " +response );
           console.log("Response is: " +response);
      }
     });
    }
  }
});

上面的事件代码呈现了一个弹出框:全部完成!您有一个新的 API key :0。控制台还呈现:Response is: 0

regenerateApiKey方法代码下方找到/server/main.js

Meteor.methods({
  regenerateApiKey: function( userId ){
    check( userId, Meteor.userId() );

    var newKey = Random.hexString( 32 );
    console.log(">>>: " +newKey);

    try {
      var keyId = APIKeys.update( { "owner": userId }, {
        $set: {
          "key": newKey
        }
      });
      console.log(">>> newKey : " +keyId);
      return keyId;

    } catch(exception) {
        console.log("FAILED UPDATE")
      return exception;
    }
  }
});

上面的方法代码在终端中呈现以下内容:

>>>: af3233a999308e39f9471b790e121cf5
>>> newKey : 0

我已将代码中的问题缩小到这一点。 keyId 变量等于“0”表明 APIKeys 集合没有得到更新。谁能解释为什么会这样?

我提供了更多信息,希望对您有所帮助。

在下面找到我订阅 /client/main.js

的代码
Router.route('/apiKey', {
 template: 'apiKey',

 waitOn: function(){
        return Meteor.subscribe('APIKey');          
    }

});

在下面找到我发布 /server/main.js

的代码
Meteor.publish( 'APIKey', function(){
  var user = this.userId;
  var data = APIKeys.find( { "owner": user }, {fields: { "key": 1 } } );

  if ( data ) {
        console.log("User: " +user+ " data is: " +data);
        console.log("Was able to find data in Publish APIKey!");
        console.log(APIKeys.find().fetch());
    return data;
  }
  return this.ready();
});

上面的发布代码在终端中呈现以下内容:

User: xELzNtMQp7u9FpZib data is: [object Object]
Was able to find data in Publish APIKey!
[]

在下面找到我声明集合的代码 imports/api/tasks.js

import { Mongo } from "meteor/mongo";
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

global.APIKeys = new Meteor.Collection("apiKeys");


/*
* Allow
*/

APIKeys.allow({
  insert: function(){
    // Disallow inserts on the client by default.
    return false;
  },
  update: function(){
    // Disallow updates on the client by default.
    return false;
  },
  remove: function(){
    // Disallow removes on the client by default.
    return false;
  }
});

/*
* Deny
*/

APIKeys.deny({
  insert: function(){
    // Deny inserts on the client by default.
    return true;
  },
  update: function(){
    // Deny updates on the client by default.
    return true;
  },
  remove: function(){
    // Deny removes on the client by default.
    return true;
  }
});

最佳答案

当您尝试更新数据库时,问题看起来是您在数据库中没有任何 key

尝试将 APIKeys.update 换成 APIKeys.upsert,如果不存在,这将创建一个 key 。

try {
  var keyId = APIKeys.upsert( { "owner": userId }, {
    $set: {
      "key": newKey
    }
  });

关于javascript - 为什么我的助手集合查询没有反射(reflect)在 html 模板中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51734346/

相关文章:

c# - 如何优雅地处理 winforms 应用程序中的休眠/ sleep 模式?

delphi - 检测 RichEdit 中 URL 的点击

xaml - Telerik:raddatetimepicker SelectedDateChanged 事件不起作用

javascript - Meteor 发布/订阅独特客户端集合的策略

javascript - 导入流式不相交联合?

javascript - 在 JS 中解构时默认嵌套部分对象吗?

meteor - 使用永远运行 meteor 生成的节点包的正确语法是什么?

node.js - 另一个 meteor 调用中的 meteor 调用

javascript - 将表单(包括文件)中的所有数据附加到 FormData

javascript - 使用 ES6 嵌套在 Javascript 中时添加对象