问题
I have a data set which is
var JobSchema = Schema({
candidates: [{
user: { type: Schema.Types.ObjectId, ref: 'User'},
status: { type: String, default: 'In Progress' },
}]
});
I want to find a specific job's _id
and update a specific candidates' field such as { _id: 123, user: 12345, status: "In Progress" }
The url for this operation is ---> localhost:3000/apply/:job_id/user_id
For example
Let say that this is the current saved data in job 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
}
How do i update only a specific field let say status
field that belong to a certain candidates' _id
in mongodb, Here's my attempt
Job.update(
{
_id: req.params.job_id,
},
{
$set: {'candidates.$.status': 'Accepted'} ,
}, function(err, count) {
if (err) return next(err);
callback(err, count);
});
I will get this error If I use the above operation.
MongoError: The positional operator did not find the match needed from the query. Unexpanded update: candidates.$.status
回答1:
$ is the solution:
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);
});
来源:https://stackoverflow.com/questions/33742316/how-do-update-a-specific-field-in-mongoose