Meteor-如何在MongoDB集合中查找/获取对象,并使用方法将其推送到另一个集合中?
我有一个服务器端方法,如:Meteor-如何在MongoDB集合中查找/获取对象,并使用方法将其推送到另一个集合中?,mongodb,meteor,methods,collections,push,Mongodb,Meteor,Methods,Collections,Push,我有一个服务器端方法,如: Meteor.methods({ 'pushInfo': function(){ if (this.userId) { userManagement.update({ '_id': this.userId }, { $push: { 'activeInfos': ["The Info/Object I want to push from another collection"] } }
Meteor.methods({
'pushInfo': function(){
if (this.userId) {
userManagement.update({
'_id': this.userId
}, {
$push: {
'activeInfos': ["The Info/Object I want to push from another collection"]
}
}
);
}
}
});
Template.available.events({
"click. push": function(e) {
e.preventDefault();
Meteor.call('pushInfo');
}
});
此方法应将对象推入集合“userManagement”内的字段“activeInfos”
我有一个点击。
事件,它会触发如下方法:
Meteor.methods({
'pushInfo': function(){
if (this.userId) {
userManagement.update({
'_id': this.userId
}, {
$push: {
'activeInfos': ["The Info/Object I want to push from another collection"]
}
}
);
}
}
});
Template.available.events({
"click. push": function(e) {
e.preventDefault();
Meteor.call('pushInfo');
}
});
现在,我有另一个名为“Infos”的集合,我想通过该方法将单个对象/ID推入字段“activeInfos”
当我用“Infos”集合中的ID手动填充该方法时,该方法的工作方式与预期的一样。它将此ID推送到“activeInfos”中,用户现在可以从“Infos”访问此objectID
但是,当方法被触发时,它应该自动从“Infos”中找到正确的ID,并将其推送到“activeInfos”中
有办法吗 如果您的
可用
模板显示了Infos
的列表,那么您可以在事件处理程序中获取Infos
对象的\u id
,并将其传递给方法:
Template.available.events({
"click. push"(e) {
e.preventDefault();
Meteor.call('pushInfo',this.InfoId);
}
});
Meteor.methods({
'pushInfo'(infoId)=>{
const info = Infos.findOne(infoId)
if (this.userId && info) {
userManagement.update(this.userId, { $push: { activeInfos: info }});
}
}
});
明白了!不过,谢谢你的努力!我不知道为什么,但我必须将this.InfoId分配给一个var,并将InfoId放入事件处理程序中的Meteor.call中。然后,我能够将这个var传递到服务器端方法中的函数中,并通过$push获取它
Template.available.events({
"click .push": function(e) {
e.preventDefault();
var InfoId = this.InfoId;
Meteor.call('pushInfo', InfoId);
}, });
及
如何像您所说的那样获得正确的ID?是的,类似于:Infos.find({“\u ID”:…}).fetch[0]。\u ID函数?也就是说,它将通过这个方法被推送。谢谢你的回答。但是我在加载localhost“unexpected token=>”时收到一个错误。我猜您在数据上下文中有一个集合,但不知道您使用的是什么键。从下面的答案来看,您似乎使用了
InfoId
来引用该对象。上面的代码已更改。