Sunday, 23 April 2017

Trying to pass new data to an object without replacing old data in mongoDB from nodejs with express

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



via Michael Ek

No comments:

Post a Comment