从属于子文档数组的子文档中拉出

时间:2016-06-15 05:54:46

标签: mongodb mongoose mean-stack

我正在开展类似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);}); 在事件中投票的所有投票。

以下是我的代码:

-abc1234567-abc.jpg

但是我收到了'不能使用部分(..)遍历元素'的错误。

我的查询/更新是否不正确?

1 个答案:

答案 0 :(得分: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以了解如何使用它。

希望这会对你有所帮助。

相关问题