Mongoose findOneAndUpdate return not updated model - mongodb

I've 1 little issue. I'm trying update model by findOneAndUpdate method. And this method works unexpected - method update model in DB but return old model (before update)
try {
const updatedLanding = await Landing.findOneAndUpdate({key: req.body.key}, {
$set: {
name: req.body.name,
}
},
).exec((err, result) => {
if (err) {
res.status(422).send({error: err});
return
}
res.send({response: result})
});
}
catch (e) {
res.status(400).send(e)
}

in mongoose query, findOneAndUpdate returns the old record that has been updated, not the updated record, the record has actually been updated, but you can not get the updated result as the query returns the old one by default, if you want to see the updated record you have to issue another query to find the record and get its updated data.

If you update document using findOneAndUpdate() hook, you'll get the old document unless you specify
{ new: true }

Related

Why mongo updates first element in db despite the condition

tell me pls why this code updates firs element in db despite the condition. And i couldn't see any logs. Im using NestJs+Typeorm+Mongo
await this.workOrderModel
.updateOne({ createRequestId: 'someMockedVaue' }, { $set: { createFlowTrackingId: 'otherValue' } })
.then((updatedWorkOrder) => {
this.logger.verbose('Updated WorkOrder: %o', updatedWorkOrder);
})
.catch((err) => {
this.logger.error('Error on update WorkOrder: %o', err);
});
I understood what the problem is, if you specify the wrong field in the filter, it takes the first user in the db and changes the data

Mongoose findOneAndUpdate() only updates if document already exists, doesn't create new doc if not?

I ran into a problem with my javascript bot, my custom prefixes don't get saved if there isn't yet a custom prefix for that server, if there is though, it does get updated correctly.
await mongo().then(async (mongoose) => {
try {
let newprefix = content.replace(`${prefix}setprefix `, '')
await prefixSchema.findOneAndUpdate({_id: guild.id}, {_id: guild.id, prefix: newprefix})
.then(async () => {
console.log(`updated prefix for guild: ${guild.id}`)
await channel.send(`Succesfully updated prefix for this server to '${newprefix}'`)
message.guild.me.setNickname(`[${newprefix}] - Helix`)
})
.catch(async (err) => {
console.error(`failed to update prefix for guild: ${guild.id}\n${err}`)
await channel.send(`Failed to update prefix.`)
})
console.log("saved to db")
} catch {
console.log("Something went wrong while saving new prefix for a server.")
} finally {
mongoose.connection.close()
}
The bot does print and send that it succesfully updated the prefix, but if there isn't already a document for the guild.id, nothing is saved. What did I do wrong and how can I solve it?
Thanks for reading!
Model.updateOne()
Parameters
[options.upsert=false] «Boolean» if true, and no documents found, insert a new document
MongoDB will update only the first document that matches filter regardless of the value of the multi option.
Use replaceOne() if you want to overwrite an entire document rather than using atomic operators like $set.
Example:
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
please visit https://mongoosejs.com/docs/api.html#model_Model.updateOne for more information.

FindAndModify: get newDocument along with info whether doc was inserted or updated

Using findAndModify:
I need to get the new resulting document
I need to know if an insert or update was done
var newUpdate = {
$set : newData,
$setOnInsert: {created_at: new Date()}
};
var options = {
upsert :true,
new: true,
};
collectionDriver.findAndModify(colName, query, newUpdate, options, function(err,resultDoc)
{
if (err) {
} else {
}
});
I get the new document, how can I know if an insert/update was happened?
One possible, though not the most efficient way, can be to check for presence of record before issuing the modify command because if you need the new record, then you cannot check if it previously existed.

Update multiple records using mongoose?

I am writing a service class (mongo_service.js) in order to keep my CRUD operations seperate for a project.
Below is the code to update multiple items.
updateMultipleCollection(Model, searchObject, collectionNewToUpdate) {
return new Promise(function (resolve, reject) {
Model.update( searchObject, collectionNewToUpdate, {new:true, multi:true}, function (err, data) {
if (err) {
reject(err);
}
resolve (data);
console.info("Multiple updates successful");
});
});
};
This works fine but the promise won't return the updated objects and I was wondering whether there was any other way to overcome this??
NOTE: In mongoose documentation they have mentioned that .update() will not return the updated objects whereas .findOneAndUpdate() does.
you could do a .find() and that will return an array.
Then do a forEach over the array and do .save on each doc. The new doc should be in the callback of .save

subsub document id returns whole document

When I findOne based on deliverables.steps._id it's returning my entire document rather than just my step with the particular id. Can I not have it return my individual step rather than the whole document? The reason I ask is so when I need to update I just update this step rather than updating the whole document each time.
exports.findStep = function(req, res) {
Project.findOne({'deliverables.steps._id': req.params.stepId}).sort('-created').exec(function(err, step) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(step);
}
});
};