2016-06-15 72 views
1

我正在開發類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);}); 

但是我收到的「不能使用的部分(..)橫貫元件」的錯誤。

我查詢/更新不正確?

回答

0

{$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知道如何使用它。

希望這會幫助你。

+1

它很好用!謝謝!我想我仍然對運營商的使用感到困惑。但我會更多地查看它。再次感謝! –