繁体   English   中英

mongoose 模式查找和更新数组子文档

[英]mongoose schema findone and update array subdocument

这是我的 mongoose 模式:

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

 '''

books 数组没有更新,newList 中的每个 object 都有 list_name,并且有不同的列表,每个列表都有自己的 books 数组,所以当添加一本书时需要更新正确的列表。

示例数据集:

  '''
            _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 将特定的 object 添加到数组中。

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

您还可以在此链接中查看 $elemMatch 的文档。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM