简体   繁体   中英

Node.js database updating object as a list

Here I want to edit the data, which is a list object. It's called operatingPrice. I need help in Node.js section. I do as attached, but it does not. How do I update operatingPrice?

    "_id": {
        "$oid": "5e9110b08e0cc20547189640"
    },
    "operations": [
        {
            "_id": {
                "$oid": "5e923bf1ca6e920bd6d46bd7"
            },
            "operationName": "cut",
            "operationPrice": 0
        }
    ]

How to update operatingPrice

router.get('/updateOperationPrice',verifyToken,(req,res)=>{
    const {operationPrice} =req.body;
                const promise = Operatings.findByIdAndUpdate({_id:req.operating_id},{ $set: { operations:{operationPrice:operationPrice} }},{new:true});
                promise.then(data=>{res.json('Update Success');})
                .catch(err=>{res.json(err);}) 
        });  
    })
});

first, findByIdAndUpdate is taking the id of the document directly, not an object like this { _id: req.operating_id } , so if you need to search by the operation Id, this is not going to work as expected, also _id is the id of the whole document, not the id of the operation item in the array, to get the _id of the operation item in the array, it should be 'operations._id'

if you need to find some document by Id, and then find only one element from the operations array in this document, we can use findOneAndUpdate , to be able to pass an object to the filter part

second, you are trying to set the operations array to an object

{ $set: { operations:{operationPrice:operationPrice} }}

this means you need to set the operations to be an object contains the operationPrice property

we need to update the price of this operation only, so we can use something like that

const promise = Operatings.findOneAndUpdate(
    { 'operations._id': req.operating_id }, // the filter part, filter by the operation._id
    { $set: {
            'operations.$.operationPrice': operationPrice // here we used the $ to update only the operation that has req.operation._id
        }
    }, 
    { new: true } // to return the document after update
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM