我在一个集合中有一个 ObjectId 数组,我想简单地添加另一个集合的 ObjectId。
router.post('/add/child', (req, res) => {
console.log(req.body);
switch (req.body.type) {
case "category":
Category.findOne({_id: req.body.to})
.then(category => {
if (!category) {
res.json({error: req.body.type + " not found"});
}
category.update({$push: {words: req.body.child}});
console.log('category', category);
res.json({category});
})
.catch(err => {
console.log(err);
res.json(err.response)
})
default:
break;
}
}
req.body 是:
{ type: 'category',
to: '5c312fd6ec0fff1c280aca19',
child: '5c323bed9b0f713aa0d49399' }
类别是:
category { words: [],
_id: 5c312fd6ec0fff1c280aca19,
title: 'Weather',
[__v: 0 }
类别模型:
category: {
title: {
type: String,
required: true
},
variation: {
type: String
},
words: [{
type: Schema.Types.ObjectId,
ref: "words"
}]
},
最佳答案
要追加数组,您需要 $push
更新方法中的 运算符,如 findOneAndUpdate
或findByIdAndUpdate
。如果您使用现有方法,则需要调用 push
数组本身的方法,然后 save
即:
Category.findById(req.body.to).then(category => {
if (!category) {
res.json({error: req.body.type + " not found"});
}
category.words.push(req.body.child);
return category.save();
}).then(updatedCategory => {
console.log('updatedCategory', updatedCategory);
res.json({ category: updatedCategory });
})
更好的原子方法是使用 findOneAndUpdate
方法如下:
Category.findByIdAndUpdate(req.body.to,
{'$push': {'words': req.body.child}},
{new: true},
)
.exec()
.then(category => {
console.log('category', category);
if (!category) {
res.json({error: req.body.type + " not found"});
}
res.json({ category });
})
.catch(err => {
console.log(err);
res.json(err.response)
})
关于node.js - 追加 ObjectId 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121699/