[英]Pull from sub-document belonging to an array of sub-document
我正在開展一個類似QA的項目。
我的問題的當前模型如下所示:
var questionSchema = new mongoose.Schema({
content: String,
answers: [{
content:String,
.
.
.
votes: [{
type: mongoose.Schema.ObjectId,
ref: 'User'
}]
}]
});
由於每個用戶都有權每個問題超過1票,我想$pull
所有的用戶在一個問題時使用事件投了票Model#update
。
以下是我的代碼:
Event.update({_id: req.params.id}, {$pull: {'answers.votes': req.user.id}}).execAsync()
.catch(err => {
handleError(res, err);
}).then(num => {
if(num === 0) { return res.send(404).end(); }
}).then(() => {exports.show(req,res);});
但我收到了'不能使用部分(..)遍歷元素'的錯誤。
我的查詢/更新不正確嗎?
{$pull: {'answers.votes': req.user.id}}
不是使用$pull
的正確方法,而是使用{$pull: {answers:{votes: req.user.id}}}
。
請嘗試以下代碼: -
Event.update({_id: req.params.id}, {$pull: {answers:{votes: req.user.id}}}).execAsync()
.catch(err =>
{
handleError(res, err);
}).then(num =>
{
if(num === 0)
{ return res.send(404).end(); }
}).then(() => {exports.show(req,res);});
請參閱$ pull-doc以了解如何使用它。
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.