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.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);
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 按不同项目对对象数组进行排序
- 使用JavaScript或jQuery检查单选按钮选择是否与数组中的项目匹配
- JS:从整个数组中每次得到5个项目,并得到平均值
- 使用圆中的数组更改背景颜色项目
- 编辑CSV数组中的项目-快速CSV node.js
- 我可以限制我添加到数组中的项目数量吗
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- 什么's JavaScript数组中项目的作用域
- 将项目放入数组中
- 使用 id 和 Javascript 从数组中删除项目
- (角度.js)如何通过过滤器计算数组中有多少项目
- 如何通过迭代对象数组来删除某些项目
- Lodash 从与值数组不匹配的数组中获取项目
- 发布要形成的 n 个项目的数组
- 查找数组中项目包含子字符串的索引
- 使用节点在 JSON 数组中搜索项目(最好不迭代)
- Javascript:从数组中删除包含带有侦听器的对象的项目的最佳方法
- 更新挖空中可观察数组中项目的属性
- JavaScript:如何在 for 循环期间跳过数组中的当前项目?(继续?