使用Node.js将数据插入MongoDb

问题描述 投票:-1回答:2

我在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)
    })
})

但是当我在邮递员中尝试时,它没用,您能帮我吗?

node.js database mongodb rest
2个回答
1
投票
collection .findByIdAndUpdate(req.params.id, {$set: { abcd: req.body.abcd }) .then(function(collection) { res.send(collection); });

0
投票

0
投票
如果使用的是mongodb驱动程序,则mongodb具有findOneAndUpdate,但没有findByIdAndUpdate。

您可以像这样使用$ push运算符:

app.put('/route/:id', function(req, res, next){ collection .findOneAndUpdate( { _id: ObjectID(req.params.id) }, { $push: { "abcd.efgh": req.body.abcd } }, { returnOriginal: false } ) .then(doc => { res.send(doc); }) .catch(err => { res.status(500).send(err); }); })

假设您已有这样的现有文档:

{ "abcd": { "efgh": [ "A", "B" ] }, "_id": "5e0326677acfbf413c2c85be" }

当您发送PUT请求以添加此文档的项目时,如下所示:

{ "abcd": "C" }

响应将是:

{ "lastErrorObject": { "n": 1, "updatedExisting": true }, "value": { "_id": "5e0326677acfbf413c2c85be", "abcd": { "efgh": [ "A", "B", "C" ] } }, "ok": 1 }

© www.soinside.com 2019 - 2024. All rights reserved.