为什么我的助手集合查询没有反映在html模板中?

时间:2018-08-07 19:43:30

标签: javascript events meteor helpers meteor-publications

在关于如何“ Write an API”的教程之后,我似乎陷入了困境,无法超越如何使生成的API密钥显示在模板中。

我在帮助器中有一个查询APIKeys.find().fetch(),该查询应正确反映在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}}"下的模板中将呈现NOTHING。我不明白为什么会这样。

在我的助手代码下找到: /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()");    
        }
     }

});

以上帮助程序代码在控制台Failed! Can't find: 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密钥的代码: /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);
      }
     });
    }
  }
});

上面的事件代码将显示一个弹出框,其中包含:All done! You have a new 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;
  }
});

1 个答案:

答案 0 :(得分:2)

问题似乎是您尝试更新它时数据库中没有任何键

尝试将APIKeys.update换成APIKeys.upsert,如果不存在则创建密钥。

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