我正试图解决这个问题好几个小时,但它只是没有工作。如何在mongo集合中的特定字段包含特定值时才运行函数?
我在一个名为“storedKeys”的集合中存储了一个“key”(和一些其他不重要的信息)作为数组字段。
这看起来像:
{
"_id" : "Company(02fd8fba13cf51cf)",
"infos" : {
"companyName" : "company",
"street" : "exampleStreet",
"number" : "123",
"city" : exampleCity",
"createdAt" : ISODate("2017-06-24T13:20:09.771Z")
},
"key" : ["123456789"]
}
现在,我想用这把“钥匙”字段权限通过调用流星方法运行在其他集合一些更新。此外,只有在storedKeys中存在正确_id的情况下才应该执行此方法。
更确切地说:如果事件处理程序放入方法调用中的变量与集合storedKeys中定义的字段匹配,则执行该方法。否则,抛出一个错误,不要执行该方法。
为此,我试着打一个提交表单的方法,比试图用一个if从句用查找({})函数在服务器端方法,像这样:
客户端(触发方法)
Template.keyCollectionThing.events({
"submit form": function (e) {
e.preventDefault();
var key = "123456789";
var id = "Company(02fd8fba13cf51cf)";
Meteor.call('updateOtherCollections', key, id);
}
});
服务器(运行方法)
Meteor.methods({
'updateOtherCollections': function(key, id) {
if(storedKeys.find({"key": key}) && storedKeys.find({"_id": id})) {
Meteor.users.update(
{'_id': this.userId
}, {
$push: {
'pushedId': id
}
});
otherDB.update(
{'_id': this.userId
}, {
$push: {
'pushedId': id
}
}
);
storedKeys.update(
{'_id': id
}, {
$set: {
"key": []
}
});
}}
});
但是,问题是,即使在storedKeys中没有密钥或storedKeys中的_id不存在,该方法始终正常运行。所以,我没有通过if()和find({})的预期验证。该方法始终执行并且集合被更新(即使没有钥匙也可以打开门)。
我非常感谢任何帮助或新的方法!
完美! .findOne()解决了这个问题,非常感谢。 – Jaybruh