I am trying to pass new data to an object without replacing the old data using nodejs. My Mongodb database (before adding new data) structure is below
{
"_id" : ObjectId("58fd05f7fb69f42d54fccd12"),
"Transaction" : {
"QRIDNumber6666" : {
"retailer" : "watson",
"discount" : "10%",
"tax" : "5%",
"Transaction Detail" : [
{
"quantity" : "1",
"pname" : "coca",
"price" : "3"
},
{
"quantity" : "3",
"pname" : "pepsi",
"price" : "5"
}
]
}
}
}
What i want to achieve is to add another QRIDNumber under Transaction, Ex: QRIDNumber 7777, which has different values but the same structure when compared to QRIDNumber6666
My current attempt is by using the following code on nodejs
app.put('/contactlist/', function (req, res) {
var id = "58fd05f7fb69f42d54fccd12";
db.CollectionName.findAndModify({
query: {_id: mongojs.ObjectId(id)},
update: {$set: {Transaction: req.body}},
new: true});
});
Note: req.body is the details and values of QRIDNumber7777 that is to be sent from my controller.
The end result from my code was it just replaced all previous content under "Transaction" (QRIDNumber6666) and replaced it with only new content(QRIDNumber7777).
I wish to have both data remain. Adding new contents under "Transaction" without deleting old ones
Okay, so assuming you'll always have an object with 1 key in req.body. Like:
req.body = {"QRIDNumber7777": {...}}
First, you need to know the name of the key:
const insertedTransactionName = Object.keys(req.body)[0]; // QRIDNumber7777
Now you can update your document without overwriting other fields.
app.put('/contactlist/', function(req, res) {
var id = "58fd05f7fb69f42d54fccd12";
db.CollectionName.findAndModify({
query: {
_id: mongojs.ObjectId(id)
},
update: {
$set: {
[`Transaction.${insertedTransactionName}`]: req.body[insertedTransactionName]
}
},
new: true
});
});
Note this line:
$set: {
[`Transaction.${insertedTransactionName}`]: req.body[insertedTransactionName]
}
Instead of overwriting whole Transaction document, you update only one nested property. So QRIDNumber6666 data still remains.
You should update your structure to Transaction array instead of creating dynamic keys.
This will help you later when you want to update the individual fields by referencing using positional operator.
So you should change your structure to
{
"_id" : ObjectId("58fd05f7fb69f42d54fccd12"),
"Transaction" : [{
"QRIDNumber": 6666,
"retailer" : "watson",
"discount" : "10%",
"tax" : "5%",
"Transaction Detail" : [
{
"quantity" : "1",
"pname" : "coca",
"price" : "3"
},
{
"quantity" : "3",
"pname" : "pepsi",
"price" : "5"
}
]
}]
}
Use $push to add the new entry 7777 into Transaction array.
app.put('/contactlist/', function (req, res) {
var id = "58fd05f7fb69f42d54fccd12";
db.CollectionName.findAndModify({
query: {_id: mongojs.ObjectId(id)},
update: {$push: {Transaction: req.body}},
new: true});
});