Почему мой запрос вспомогательной коллекции не отражается в шаблоне html?

Следуя руководству о том, как "написать 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>

In the template above, NOTHING is rendered in the template under value="{{apiKey}}". I dont understand why this is.

Найдите ниже код моих помощников: /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;
  }
});

person SirBT    schedule 07.08.2018    source источник


Ответы (1)


Проблема выглядит так, как будто у вас нет ключей в базе данных, когда вы пытаетесь ее обновить.

Попробуйте заменить APIKeys.update на APIKeys.upsert, что создаст ключ, если он не существует.

try {
  var keyId = APIKeys.upsert( { "owner": userId }, {
    $set: {
      "key": newKey
    }
  });
person Fred Stark    schedule 08.08.2018
comment
Большое спасибо, что разобрались с этим! Меня это напрягало несколько дней! - person SirBT; 08.08.2018