Reputation: 3
I am looking to update mongodb document using findOneAndUpdate
not sure of it right now.
My Document example:
"_id" : ObjectId("5860f0ec197e7a05812fbddd"),
"username" : "krapali",
"last_updated" : ISODate("2016-12-26T10:29:00.557Z"),
"max" : 6,
"min" : 6,
"data" : [{
"dataAdded" : {
"min" : 6,
"max" : 6,
},
"dataAdded" : {
"min" : 5,
"max" : 7,
}
}],
"data_count" : 2
If you observe above sample document, you will see it array of object.
Whenever I try to update my document I will be having 3 fields with me username, max and min
. depending on username I need to add/push into data array a new element as well as I need to update min and max field and increase data count by one each new update.
Can some will help me how to do it?
Upvotes: 0
Views: 105
Reputation: 8858
Its very easy to use findOneAndUpdate method
modal.findOneAndUpdate({username: username},{
$push: {
data: {
dataAdded: {
min: minValue,
max: maxValue
}
}
},
$set: {
min: minValue,
max: maxValue
},
$inc: {
data_count: 1
}
},{
upsert: false,
new: true
}, function( err, doc ) {
});;
Upvotes: 0
Reputation:
The logic is very simple. first, make a call to db to get the document which you want to update and create a variable update
here whatever updates need to be done. And just use findOneAndUpdate
.
// input to function username, min and max
modal.findOne({username: username}, function(err, data){
var minmax = {dataAdded: {min: min, max:max}};
var update = {
$push: {
data: minmax
}
};
update.$set = {
data_count: data.data.length + 1,
max: max,
min: min
};
modal.findOneAndUpdate({username: username}, update, {new: true}, function(err. updatedDoc){
// do whatever you want with updated document
})
})
Upvotes: 0