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
In general, you should use save () to update a document in Mongoose, unless you need an atomic update. Here's a summary of the key features of all 4 ways to update a document: Want to become your team's MongoDB expert?
Unlike updateOne (), it gives you back the updated document. In general, you should use save () to update a document in Mongoose, unless you need an atomic update.
Update only specific fields in MongoDB? Update only specific fields in MongoDB? To update only specific field, you can use $set operator. Let us first create a collection with documents
You need to either create () or use find () to get a document. Second, Mongoose documents have change tracking. Under the hood, when you call doc.save (), Mongoose knows you set title and transforms your save () call into updateOne ( { $set: { title } }).
$
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With