I am sending a new item to the database and inside that data there is an array with some id. I'm using node and expressJs. So, the idea is If there is an object exists, I want to update the array inside the object. Or the object will be created in mongodb.
The Issue is: On first submit it adds to the database with an array. But on other clicks the array just got replaced with new Id.
app.put("/destination", async (req, res) => {
const email = req.query.email;
const query = { email: email };
let result;
if (query) {
const cursor = userCarCollection.find(query);
const userNewIds = req.body;
result = await collection.updateOne(
query,
{ $set: userNewIds },
{ upsert: true }
);
} else {
result = await carCollection.insertOne(userNewCar);
}
res.send(result);
});
I found the solution guys. Sorry for any inconvenience. I had to use $push method not $set method. As, I am a beginner I couldn't think that way.
My solution is as follows and it's working perfectly:
if (query) {
const cursor = userCarCollection.find(query);
const userNewIds = req.body.productId.toString();
result = await userCarCollection.updateOne(
query,
{
$push: {
productId: userNewIds,
},
},
{ upsert: true }
);
}