简体   繁体   English

使用 Nodejs 向 MongoDb 插入数据

[英]Inserting Data to MongoDb using Nodejs

I have couple of objects inside my Mongodb in a collection example of an object is :我的 Mongodb 中有几个对象,在一个对象的集合示例中:

_id: xxxxxxxxxxxxxxxxxxxx
abcd:
    efgh: " "

where abcd is an object which contains array of efgh and I want to push data inside the array efgh (which means add data into that particular _id and into efgh when that api is triggered)其中abcd是一个包含efgh数组的对象,我想将数据推送到数组efgh (这意味着在触发该api时将数据添加到该特定 _id 和 efgh 中)

I wrote an api for that我为此写了一个api

app.put('/route/:id', function(req, res, next){
    //console.log(req.params.id)
    console.log(req);
    collection.findByIdAndUpdate({abcd:req.params.id}, req.body.abcd).then(function(collection){
        res.send(collection)
    })
})

but when I tried it in postman it didn't work can u please help me with this.但是当我在邮递员那里尝试它时它不起作用,请您帮我解决这个问题。

Your second arguments must use $set and the first argument must match for the id:您的第二个参数必须使用$set并且第一个参数必须与 id 匹配:

collection
  .findByIdAndUpdate(req.params.id, {$set: { abcd: req.body.abcd })
  .then(function(collection) {
    res.send(collection);
  });

If you want yo push inside array, MongoDB provides $push or $addToSet.如果你想在数组中推送,MongoDB 提供了 $push 或 $addToSet。

collection.findByIdAndUpdate({_id :req.params.id}, {$addToSet: { "abcd.efgh": req.body.abcd.efgh } }).then(function(collection){
    res.send(collection)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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