Node.js 使用Nodejs向MongoDb插入数据

Node.js 使用Nodejs向MongoDb插入数据,node.js,database,mongodb,rest,Node.js,Database,Mongodb,Rest,我的Mongodb中有两个对象,一个对象的示例是: _id: xxxxxxxxxxxxxxxxxxxx abcd: efgh: " " 其中abcd是一个包含efgh数组的对象,我想在数组efgh中推送数据(这意味着在触发api时将数据添加到该特定的_id和efgh中) 我为此编写了一个api app.put('/route/:id', function(req, res, next){ //console.log(req.params.id) console.log

我的Mongodb中有两个对象,一个对象的示例是:

_id: xxxxxxxxxxxxxxxxxxxx
abcd:
    efgh: " "

其中
abcd
是一个包含
efgh
数组的对象,我想在数组
efgh
中推送数据(这意味着在触发
api
时将数据添加到该特定的_id和efgh中)

我为此编写了一个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)
    })
})

但是当我在《邮递员》中试用时,它不起作用。请帮我解决这个问题。

您的第二个参数必须使用
$set
,并且第一个参数必须与id匹配:

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

如果您想在阵列内推送,MongoDB提供$push或$addToSet

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

请检查条件{u id:“5DB6B2670F133B65DBBE459”}@MaheshBhatnagar我检查了它,但没有工作{abcd:req.params.id}错误的条件,请告诉响应是什么?@MaheshBhatnagar未处理PromiseEjectionWarning:CastError:在模型“collection”的路径“\u id”处对值“{abcd:“5DB6B2670F133B65DBBE459}”强制转换为ObjectId失败在新的CastError{u id:ObjectId(“5db6b26730f13b65dbbe459”)}中使用ObjectId关键字