gpt4 book ai didi

node.js - Mongoose 在一个查询中更新或创建多个值

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:46 25 4
gpt4 key购买 nike

我有一个这样的文档:

{
"_id" : ObjectId("565e906bc2209d91c4357b59"),
"userEmail" : "abc@example.com",
"subscription" : {
"project1" : {
"subscribed" : false
},
"project2" : {
"subscribed" : true
},
"project3" : {
"subscribed" : false
},
"project4" : {
"subscribed" : false
}
}
}

我正在使用express来进行我的post网络服务调用,如下所示:

router.post('/subscribe', function(req, res, next) {
MyModel.findOneAndUpdate(
{
userEmail: req.body.userEmail
},
{
// stuck here on update query
},
{
upsert: true
}, function(err, raw) {
if (err) return handleError(err);
res.json({result: raw});
}
)
});

我的req包含如下数据:

{
userEmail: "abc@example.com",
subscription: ["project1", "project4"]
}

以下是我想在这次通话中执行的步骤:

  1. 检查用户是否存在,否则创建用户。例如,如果 abc@example.com 不存在,则创建一个新文档,其中 userEmail 为 abc@example.com

  2. 如果用户存在,请检查subscription对象中是否存在project1project4。如果没有创建那些。

  3. 如果 subscription 中存在 project1project4,则将 subscribed 更新为 true

我不确定是否可以通过单个查询实现上述所有 3 个步骤。请指教。

最佳答案

维玛拉杰,

您可以使用 $set 来完成此操作。 $set 运算符将字段的值替换为指定值。根据文档:

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

由于您的 req.subscription 将是一个数组,因此您必须构建查询。看起来像这样:

{ 
$set: {
"subscription.project1":{"subscribed" : true},
"subscription.project4":{"subscribed" : true}
}

您可以使用reducereq.subscription = ["project1","project4"] 数组创建对象

var subscription= req.subscription.reduce(function(o,v){
o["subscription." + v] = {subscription:true};
return o;
},{});

然后你的代码变成:

router.post('/subscribe', function(req, res, next) {

var subscription= req.subscription.reduce(function(o,v){
o["subscription." + v] = {subscription:true};
return o;
},{});

MyModel.findOneAndUpdate(
{
userEmail: req.body.userEmail
},
{
$set: subscription
},
{
upsert: true
}, function(err, raw) {
if (err) return handleError(err);
res.json({result: raw});
}
)
});

关于node.js - Mongoose 在一个查询中更新或创建多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042583/

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