I am trying to update a mongodb user document. It is as below
{
"_id":"123",
"email":"sam@example.com"
}
I want to add one field 'name' to this document.
My code is as below
async function test() {
const user = {"_id":"123", "email" : "sam@example.com" };
async function setUsername(user, update) {
await userCollection.updateOne(user, update);
}
await setUsername(user, { $set: { name: "sam"} });
}
test();
However, when I see in the db, I am not able to see the field set in the document.
I am sure I am missing someway how the node driver is implemented, but I am not sure of the issue.
I have even tried using upsert: true option which gave me an error as the document was already existing.
I guess I had given the function name wrong and I didn't create the document before.
posting the final snippet that works:
const { MongoClient } = require("mongodb");
async function test() {
const mclient = await MongoClient.connect("mongodb://localhost:27017/?w=1", {
useNewUrlParser: true
});
const db = mclient.db("test");
const userCollection = db.collection("user");
const user = { _id: "123", email: "sam@example.com" };
function setUsername(user, update) {
return userCollection.updateOne(user, update);
}
await setUsername(user, { $set: { name: "sam" } });
}
(async () => {
test();
})();