这一点.提交后未插入MongoDB属性

this.userId is undefined MongoDB property not inserted after submit

本文关键字:MongoDB 属性 插入 提交 这一点      更新时间:2023-09-26

我的客户端文件中有以下事件:

Template.categories.events({
...
  'keyup #add-category': function (e,t){
    if (e.which === 13)
    {
      var catVal = String(e.target.value || "");
      if (catVal)
      {
        lists.insert({Category:catVal,owner:this.userId});
        Session.set('adding_category', false);
      }
    }
  },
  ...
});

这是相关的模板部分:

<template name="categories">
    <div id="categories" class="btn-group">
        {{#if new_cat}}
        <div class="category">
            <input type="text" id="add-category" value="" />
        </div>
        {{else}}
        <div class="category btn btn-inverse" id="btnNewCat">&plus;</div>
        {{/if}} 
        {{#each lists}}
        <div class="category btn {{list_status}}" id="{{_id}}">     
            {{Category}}
        </div>
        {{/each}}
    </div>
</template>

所以当插入一个新的Category时,应该设置owner ..但它没有。

MongoDB中的条目:

> db.lists.find()
{ "Category" : "test-admin", "_id" : "EsybjC3SLnNzCBx2t" }

知道我做错了什么吗?(实际上,我正在遵循"Getting Started with Meteor"图书借阅库示例

编辑似乎:

console.log(this.userId);
undefined

换行:

lists.insert({Category:catVal,owner:this.userId});

:

lists.insert({Category:catVal,owner:Meteor.userId()});

this可能不是您在该事件中所期望的。您应该调试以确认情况是否如此。this.userId可能没有定义。我建议将this分配给这个事件处理程序函数之外的变量(称为"自我"或"那个"),但在this将是您实际想要的范围内。然后可以在事件处理程序中引用该变量。

应该是这样的:

function thatRegistersEvents() {
    var self = this;
    // ...
    registerSomeEvent(function () {
        return self.someThisProperty;
    });
}

这是正确的行为。如果您阅读官方的Meteor文档以获取this.UserId的引用,那么它只在Meteor.publish()Meteor.methods()中可用。this.UserIdMeteor.template()中不可用,这在上面的代码示例中已经完成了,因此必须在模板中使用Meteor.userId()