The findOneAndUpdate method doesn't work properly. I'm trying to update all the fields all at once but it's only updating (setting) the last field. It's always only the last field. Can someone tell me what I'm doing wrong or what can I do to have the expected effect?
This is my findOneAndUpdate code:
Book.findOneAndUpdate({_id:bookId},{$set:{"name": name},$set:{"genre": genre},$set:{"author": author},$set:{"similar": similar}}).exec(function(err, book){
if(err){
console.log(err);
res.status(500).send(err);
} else {
res.status(200).send(book);
}
});
You are using the $set operator multiple times. The correct syntax for $set is :
{ $set: { <field1>: <value1>, ... } }
You need to change your update argument like this:
Book.findOneAndUpdate({ "_id": bookId }, { "$set": { "name": name, "genre": genre, "author": author, "similar": similar}}).exec(function(err, book){
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.status(200).send(book);
}
});
Related
I am facing an issue with mongoose "findOneAndUpdate" query. Following is the schema structure of my document.
{
"_id": "5fe2b6145dcd48c505000590",
"email": "user1#mail.com",
"todos": [
{
"_id": "5fe2b990fb9d7055c46d83a4",
"text": "important task",
"status": "in-progress"
}
]
}
I am trying to remove the todo object from the "todos" array of objects by the email and _id of that particular object. following is the code I am using.
let { task_id, email } = req.body
UserModel.findOneAndUpdate({ email : email},
{
$pull : {
todos : {
_id : task_id
}
}
},
{ safe: true, new: true },
function(err, model) {
if(err){
return res.send(err)
}
return res.send(model)
}
)
The above code is just returning the preset document, not removing the object from the todos array.
what is wrong with the above code?
I am doing currently doing as
if (part.qty) {
part.status = 'In Stock';
}
const part = new partsModel(part);
return part.save();
is it possible do this in MongoDB query only without using if statement both insert and update
You can try something like:
const filterObj = {
"$or": [{
"qty": {
"$exists": true
}
}, {
"qty": {
"$ne": null
}
}, {
"qty": {
"$ne": 0 //based on what type of value you have in qty
}
}]
};
const updateObj = {
"$set": {
"status": "In Stock"
}
};
partsModel.update(filterObj, updateObj)
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
This will update the first matching record with our filters. If you wanna update all matching records use updateMany() instead.
Check out the official mongoose docs for more details.
P.s: You may need some modifications as i couldn't get a chance to try the code. hope this helps :)
I want to update a array value but i am not sure about the proper method to do it ,so for i tried following method but didnt worked for me.
My model,
The children field in my model
childrens: {
type: Array,
default: ''
}
My query,
Employeehierarchy.update({ _id: employeeparent._id} ,{ $set: {"$push": { "childrens": employee._id }} })
.exec(function (err, managerparent) {});
Can anyone please provide me help.Thanks.
You can't use both $set and $push in the same update expression as nested operators.
The correct syntax for using the update operators follows:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
where <operator1>, <operator2> can be from any of the update operators list specified here.
For adding a new element to the array, a single $push operator will suffice e.g. you can use the findByIdAndUpdate update method to return the modified document as
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{ "$push": { "childrens": employee._id } },
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
Using your original update() method, the syntax is
Employeehierarchy.update(
{ "_id": employeeparent._id},
{ "$push": { "childrens": employee._id } },
function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
}
);
in which the callback function receives the arguments (err, raw) where
err is the error if any occurred
raw is the full response from Mongo
Since you want to check the modified document, I'd suggest you use the findByIdAndUpdate function since the update() method won't give you the modified document, just the full write result from mongo.
If you want to update a field in the document and add an element to an array at the same time then you can do
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{
"$set": { "name": "foo" },
"$push": { "childrens": employee._id }
}
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
The above will update the name field to "foo" and add the employee id to the childrens array.
can follow this
if childrens contains string values then model can be like:
childrens: [{
type : String
}]
if childrens contains ObjectId values of another collection _id and want populate then model can be like:
childrens: [{
type : mongoose.Schema.Types.ObjectId,
ref: 'refModelName'
}]
no need to use $set just use $push to insert value in childrens array. so query can be like:
Employeehierarchy.update(
{ _id: employeeparent._id},
{"$push": { "childrens": employee._id } }
).exec(function (err, managerparent) {
//
});
This will help I guess
Employeehierarchy.findOneAndUpdate(
{ _id:employeeparent._id },
{ $set: { "childrens": employee._id }}
)
I have tried quite a few combinations and checked the MongoDB 3.2 docs, but I still am not getting my new Date() stored in my DB. Everything else below is getting properly stored. Thanks in advance for any tips!
Code from my app.js file:
db.collection('users').update({user: req.user.username}, {
$push: {
"recentPlays": {
"quiz": req.session.mostRecentQuiz,
"score": score
}
}
},{
$set: {
"mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
"mostRecentQuiz.time" : new Date() // StackOverflow: this is the part that is not getting stored in the DB.
}
}, function (err, result) {
if (err) throw err;
console.log(result);
});
Your update method is being called the wrong way, the update operators $set and $push should be in the same document. Re-write your method as:
db.collection('users').update(
{ "user": req.user.username },
{
"$push": {
"recentPlays": {
"quiz": req.session.mostRecentQuiz,
"score": score
}
}
"$set": {
"mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
"mostRecentQuiz.time" : new Date()
}
}, function (err, result) {
if (err) throw err;
console.log(result);
}
);
coordinatesCollection.findOne({
"unique_id": unique_id,
}, function(err, object) {
if (object) {
coordinatesCollection.update({
"unique_id": unique_id
}, {
$push: {
coordinates: {
"coordinateX": msg.coordinatex,
"coordinateY": msg.coordinatey,
"ms_time": ms_time,
"page": msg.page,
}
}
})
} else {
coordinatesCollection.insert({
"unique_id": unique_id,
"coordinates": [{
"coordinateX": msg.coordinatex,
"coordinateY": msg.coordinatey,
"ms_time": ms_time,
"page": msg.page,
}]
})
}
});
});
The objective of this code is: If unique_id exists add coordinateX, coordinateY, ms_time and page to coordinates arrays if not exists insert unique_id and new array to coordinates.
When I saw the collection I found multiple documents with the same unique_id.
What is wrong ?
For this problem I suggest You to use instead only update function with $exists statement in query.