I'm trying to use findOneAndUpdate() but can't seem to get it to work. Here's the query I'm using. It adds an object to an 'items' array nested inside of a 'lists' array for a particular entry with 'username'. I've tried it with a simple $set for a field not inside of a nested array, and it also doesn't seem to work. Currently no errors are being returned.
MongoClient.connect(
uri,
{ useUnifiedTopology: true },
(err, db) => {
if (err) throw err;
var dbo = db.db("Todolist");
dbo.collection("Users").findOneAndUpdate(
{
username: username,
lists: {
$elemMatch: {
name: listName,
},
},
},
{
$push: {
"lists.$.items": {
title: title,
description: description,
dueDate: dueDate,
priority: priority,
completed: false,
},
},
}
);
},
(err, doc) => {
if (err) res.send("/addListItem failed");
else res.send("/addListItem successful");
}
);
} catch (e) {
console.error(e);
}
You have to use .dot
notation along with the $
positional operator here
Schema.findOneAndUpdate(
{ username: username },
{ "lists.$.name": listName }
)
It turned out that the answer to my problem was bracket placement. I placed the callback after the closing )
for the function arguments to findOneAndUpdate
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.