Application to control expenses. I write an object to a collection in the MongoDB database which contains the username and another object – the categories for which he spent money. How can I add one category to the categories object? I tried via findOneAndUpdate but it overwrites all categories and you need to specify all categories to search. How can I write one category to a user’s categories object?
let users = [
{
name: "Bob",
сategories: {
eat: "20$",
entertainment: "100$",
},
},
{
name: "Alice",
сategories: {
products: "50$",
},
},
];
mongoClient.connect(function (err, client) {
if (err) return console.log(err);
const db = client.db("expensesdb");
const col = db.collection("users");
col.findOneAndUpdate(
{
сategories: {
eat: "20$",
entertainment: "100$",
},
},
{
$set: {
сategories: {
products: "100$",
},
},
},
function (err, result) {
console.log(result);
client.close();
}
);
});
2
Answers
Use
dot
notationPlayground
Modify your query using dot notation.