簡體   English   中英

從屬於子文檔數組的子文檔中拉出

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM