从属于子文档数组的子文档中提取

Pull from sub-document belonging to an array of sub-document

我正在从事类似质量检查的项目。

我的问题的当前模型如下所示:

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);});

但是我收到了'cannot use the part (..) to traverse the element'的错误。

我的query/update不正确吗?

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

希望对您有所帮助。