Meteor:如何将项目推送到用户集合并创建列表或数组,而不是用新项目替换每个项目

Meteor: How can i push items to users collections and create a list or array instead of replacing each item with the new one?

本文关键字:项目 数组 替换 新项目 列表 创建 合并 集合 用户 Meteor      更新时间:2023-09-26

我正在尝试通过单击事件将另一个集合中的对象附加到 Meteor.user 集合。我有一个集合,其中包含一个名为"类别"的项目列表,每个类别都有一个名称字段,我想将其名称推送到meteor.user中。

它应该以一种用户可以根据需要推送任意数量的名称的方式工作,但它只接受一个条目,当我单击另一个名称时,新名称将替换旧名称,而不是数组。 我怎样才能让它允许许多条目?

客户端/用户.js

Template.CategoriesMain.events({
  'click .toggle-category': function(e){
          //var id = $(e.target).attr('posts.name');
          var id = $(e.target).parent().find("a").text();
          console.log(id);
          e.preventDefault();
          Meteor.call('addingCategory', id, function(error, user){ console.log(id)});
      }
});

服务器/用户.js

Meteor.methods({
    addingCategory: function(name) {
      var cats = [{}];
      cats.push(name);
        console.log(Meteor.userId());
        Meteor.users.update({
      _id: Meteor.userId()
    }, {
      $set: {
        name: name
      }
    });
    }
});

这是来自db.user.find()的用户,如您所见

"姓名" : "A-里斯"

它显然推动了名称,但我无法添加更多,我只能替换

{ "_id" : "4CHcZjSD4hCrqweGA", "createdAt" : ISODate("2016-07-13T21:38:59.505Z"), "服务" : { "密码" : { "隐秘" : "$2a$10$lKZtrYSMD4EGPj6eamgFDuPZ41Jw52DgivBly3lUYWbGDtfZBg1X." }, "恢复" : { "登录令牌" : [ { "何时" : ISODate("2016-07-13T21:38:59.719Z"), "hashedToken" : "BsqTGedB2FkmSPO3+5I31rOM2+MPtF97Zc9tRQ4pf8Y=" } ] } }, "emails" : [ { "地址" : "mun@les.com", "已验证" : 假 } ], "角色" : [ "discoveror", "yes" ], "isAdmin" : true, "name" : "a-reece" }

如何添加更多名称而不是替换?

编辑

Meteor.methods({
    addingCategory: function(name) {
        //Meteor.users.update(Meteor.userId(), { $addToSet: { name: name} } );
        console.log(Meteor.userId());
        //Meteor.users.update(Meteor.userId(), { $set: { "categories": cats }} );
        Meteor.users.update({
      _id: Meteor.userId()
    },
      {
        $unset: {
            name: name
        }
      },
    {
      $addToSet: {
        name: name
      }
    });
    }
});

 Template.CategoriesMain.events({
  'click .toggle-category': function(e){
          //var id = $(e.target).attr('posts.name');
          var ob = $(e.target).parent().find("a").text();
          var id = $.makeArray( ob );
          console.log(id);
          e.preventDefault();
          Meteor.call('addingCategory', id, function(error, user){ console.log(id)});
      }
});

您当前正在执行:

Meteor.users.update({ _id: Meteor.userId() }, { $set: { name: name } });

您有两种选择:$push$addToSet

Meteor.users.update({ _id: Meteor.userId() }, { $push: { name: name } });

Meteor.users.update({ _id: Meteor.userId() }, { $addToSet: { name: name } });

前者推送到阵列上,允许重复,后者避免欺骗。

您不需要:

var cats = [{}];
cats.push(name);