Stack Overflow Asked by Niaz M. Sameer on November 7, 2021
I’m trying to update a document in a Mongo database using the MongoDB NodeJS Driver. Here’s the code:
/**
* Find a document with the specified filter and update it's data.
* @param {string} collectionName The name of the collection to perform the operation in.
* @param {object} filter The filter to find the document with.
* @param {object} update The data to update the document with.
* @param {object} options Optional settings. Refer to http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne
* @returns {Promise<object|mongodb.MongoError>} A promise that resolves with the result object or rejects with a MongoError.
*/
const updateDocument = (collectionName, filter, update, options) => {
return new Promise((resolve, reject) => {
const collection = db.collection(collectionName);
// collection.updateOne(filter, update, options, (error, result) => {
// // Resolve promise with result if error is null
// // Else reject promise with error
// return resolve(result) ? error == null : reject(error);
// });
collection.findOneAndUpdate(filter, update, options, (error, result) => {
// Resolve promise with result if error is null
// Else reject promise with error
return resolve(result) ? error == null : reject(error);
});
});
};
db.updateDocument('homepage-settings', { setting: setting }, { value: value }, { upsert: true }).then((result) => {
resolve(result);
}).catch((error) => {
reject(error);
});
});
However, the result is undefined and the document is not updated and no new document is created
did you try like this?
https://docs.mongodb.com/manual/reference/method/db.collection.updateOne
db.members.updateOne(
{ _id: 1 },
[
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ], lastUpdate: "$$NOW" } },
{ $unset: [ "misc1", "misc2" ] }
]
)
Answered by Misha Avetisyan on November 7, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP