I need to write down a category and its cost in category object. Now, in my code example, I am adding the products: $50 category to the user. After execution, ‘categories’: { products: ’50$’ } is displayed in the console. But if you add products: 1000$ again, it will overwrite and output ‘categories’: { products: ‘1000$’ }. And I need to display ‘categories’: { products: ‘$50’ , products: ‘$1000’ }. How can this be implemented?
JavaScript
x
20
20
1
mongoClient.connect(function (err, client) {
2
if (err) return console.log(err);
3
4
const db = client.db("db");
5
const col = db.collection("coll");
6
col.findOneAndUpdate(
7
{
8
name: "User1",
9
},
10
{
11
$set: {
12
"сategories.products": "50$",
13
},
14
},
15
function (err, result) {
16
console.log(result);
17
client.close();
18
}
19
);
20
});
Advertisement
Answer
Instead of
JavaScript
1
4
1
$set: {
2
"сategories.products": "50$"
3
}
4
use
JavaScript
1
6
1
$addToSet: {
2
сategories: {
3
products: "1000$"
4
}
5
}
6