gpt4 book ai didi

javascript - 如何仅在 Mongo 集合中的特定字段包含特定值时运行函数?

转载 作者:行者123 更新时间:2023-12-01 03:27:32 25 4
gpt4 key购买 nike

我将“ key ”(以及其他一些不重要的信息)作为数组字段存储在名为“storedKeys”的集合中。

这看起来像:

{
"_id" : "Company(02fd8fba13cf51cf)",
"infos" : {
"companyName" : "company",
"street" : "exampleStreet",
"number" : "123",
"city" : exampleCity",
"createdAt" : ISODate("2017-06-24T13:20:09.771Z")
},
"key" : ["123456789"]
}

现在,我想使用这个“关键”字段作为通过调用 Meteor 方法在其他集合中运行某些更新的权限。此外,只有在storedKeys中存在正确的_id时才应执行此方法。

更准确地说:如果事件处理程序放入方法调用的变量与存储键集合中定义的字段匹配,则执行该方法。否则,抛出错误并且不执行该方法。

为此,我尝试通过提交表单调用方法,然后尝试在服务器端方法中使用带有 find({}) 函数的 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({}) 没有进行我所期望的验证。该方法始终会执行,并且集合会更新(甚至无需 key 即可开门)。

最佳答案

.find() 返回一个光标,它是一个函数,并且始终为真实。 p>

如果您希望找到单个文档,请使用.findOne()。如果您期望找到> 0,那么您可以测试.find(query).count()(0将为假,任何其他数字将为真)

关于javascript - 如何仅在 Mongo 集合中的特定字段包含特定值时运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com