猫鼬模式 findone 和更新数组子文档

mongoose schema findone and update array subdocument

这是我的猫鼬模式:

userId 是 Okta 为用户配置文件生成的唯一编号。 '''

var book_listSchema = new mongoose.Schema({

userId:{type: String, required: true},
first_name: { type: String, required: true},
last_name:{ type: String, required: true},
newList: [{

         list_name: String,
         books:
    [{
        book_name: {type: String, required: true},
        book_author: {type: String, required: true},
        date_added: {type: Date, default: Date.now},
        date_finished: {type: Date, default: Date.now},

    }]}],


    });

'''
   

这是我用来查找和更新的代码,将一本书添加到书籍数组中。

 '''
 book_list.findOneAndUpdate({"userId": req.userContext.userinfo.sub, newList:{"newList.list_name": list_name}}, {$push:{books:{book_name: title, book_author:author, date_added: new Date()}}}

 '''

书籍数组没有更新,newList 中的每个对象都有 list_name,并且有不同的列表,每个列表都有自己的书籍数组,因此在添加书籍时需要更新正确的列表.

示例数据集:

  '''
            _id:625c81d7622b044fb297ce54

             userId:"00uvgyn7OikAwud6"
             first_name:"John"
             last_name:"Smith"
             newList:Array
                 0:Object
                   list_name:"read"
                   books:Array
                      0:Object
                      book_name:"The Great Gatsby"
                      book_author:"Francis Scott Fitzgerald"
                      date_added:2022-04-19T00:43:24.248+00:00
                     _id:625e05ac083663dc44f37804
                    date_finished:2022-04-19T00:43:24.252+00:00
                    _id:625e05ac083663dc44f37803
                    __v:0
  '''

正确的方法是:

db.collection.update({
  userId: "00uvgyn7OikAwud6",
  newList: {
    $elemMatch: {
      list_name: "read"
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: "a new book",
      book_author: "some author",
      date_added: new Date()
    }
  }
})

或以您的代码方式

db.collection.update({
  userId: req.userContext.userinfo.sub,
  newList: {
    $elemMatch: {
      list_name: list_name
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: title,
      book_author: author,
      date_added: new Date()
    }
  }
})

$elemMatch 允许您匹配同一数组元素中的多个组件,然后您可以使用 $push 将特定对象添加到数组中。

您可以在此处 运行 检查相同的查询 https://mongoplayground.net/p/YnzDRfhwpEt

您还可以在 link.

中查看 $elemMatch 的文档

如果您遇到任何问题,请告诉我。