gpt4 book ai didi

node.js - 如何更新 Mongoose 中的特定字段?

转载 作者:IT老高 更新时间:2023-10-28 13:25:46 27 4
gpt4 key购买 nike

我有一个数据集

var JobSchema = Schema({
candidates: [{
user: { type: Schema.Types.ObjectId, ref: 'User'},
status: { type: String, default: 'In Progress' },
}]
});

我想查找特定job的_id并更新特定候选人的字段,例如{ _id: 123, user: 12345, status: "In Progress"}

这个操作的url是---> localhost:3000/apply/:job_id/user_id

例如

假设这是作业mongodb中当前保存的数据

  { 
"_id" : 123, ---> job_id

"candidates" :
[{
"_id" : 234 ,
"user": 345 , --> user_id
"status" : "In Progress"
},

{
"_id" : 345 ,
"user": 678 , --> user_id
"status" : "In Progress"
}]
"__v" : 0
}

我如何只更新一个特定的字段,比如说 status 字段属于 mongodb 中某个候选人的 _id,这是我的尝试

          Job.update(
{
_id: req.params.job_id,
},
{
$set: {'candidates.$.status': 'Accepted'} ,
}, function(err, count) {
if (err) return next(err);
callback(err, count);
});

如果我使用上面的操作,我会得到这个错误。

MongoError:位置运算符未从查询中找到所需的匹配项。未扩展更新:candidate.$.status

最佳答案

$是解决方案:

Job.update(
{
_id: found._id,
'candidates.user': req.params.user_id
},
{
$set: { 'candidates.$.status': 'Accepted'} },
}, function(err, count) {
if (err) return next(err);
callback(err, count);
});

关于node.js - 如何更新 Mongoose 中的特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33742316/

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