我在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)
})
})
但是当我在邮递员中尝试时,它没用,您能帮我吗?
collection
.findByIdAndUpdate(req.params.id, {$set: { abcd: req.body.abcd })
.then(function(collection) {
res.send(collection);
});
您可以像这样使用$ 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 }