【问题标题】:mongoose/mongodb subdocument deep query and updatemongoose/mongodb 子文档深度查询和更新
【发布时间】:2018-04-05 19:18:28
【问题描述】:

架构

var chapterSchema = new Schema({_id: Number, completed: Boolean}) 
var bookSchema = new Schema({  date: { type: Date, default: Date.now }, author: String,  chapter: chapterSchema })
var personSchema = new Schema({ _id: Number, name: String, books: [bookSchema] })

示例对象(人物对象)

{
  _id: 1,
  name: Bond,
  books: [{
    date: ISODate("2017-10-24T19:01:18.362Z”),
    author: Martin,
    chapter: {}
  }]
}

子文档(章节对象)

var chapter = new chapterSchema({_id: 1, completed: true})

要求

我想将章节对象添加到示例对象(person.books)中

预期

{
  _id: 1,
  name: Bond,
  books: [{
    date: ISODate("2017-10-24T19:01:18.362Z”),
    author: Martin,
    chapter: {
      _id: 1,
      completed: true
    }
  }]

试过

let todayStart = new Date()
todayStart.setHours(0,0,0,0)

Patient.findOneAndUpdate({'_id': 1, ‘books.date': { $not: { $gt: todayStart } } }, {$set: {‘books.$.chapter’: chapter}}, {new: true, upsert: true}, (err, consultation) => {
  if (err) {
    console.error(‘[UPDATE] Failed to add chapter')
  } else {
    console.log(‘[UPDATE] chapter is added)
  }
})

我收到“添加章节失败”错误

所以,我尝试使用 findOne 来获取书籍子文档中的任何字段。

Patient.findOne({'_id': 1, ‘books.date': { $gt: todayStart } }, {“books.$.author”: 1}, (err, data) => {
  if (err) console.log('[find] data not found')
  console.log('[FIND]' + JSON.stringify(data)
})

它给了我以下结果,

{_id: 1, books: [{ date: ISODate("2017-10-24T19:01:18.362Z”), author: Martin, chapter: {} }]}

但是,我期待这里只有作者。

最后,我想知道如何将对象插入到 Mongodb/Mongoose 的子文档中。

P.S: new Date() 我是从 express.js 得到的,不过在这里没关系。

【问题讨论】:

    标签: node.js mongodb mongoose insert-update subdocument


    【解决方案1】:

    这可以帮助你:

    db.yourDb.update(
        {
            "_id": 1,
            "books": {
                "$elemMatch": {
                    "date": {
                        "$lte": ISODate("2017-10-24T20:01:18.362+0000")
                    }
                }
            }
        },
        {
            "$set": {
                "books.$.chapter": { "_id": 1, "completed": true }
            }
        }
    )
    

    请记住,如果不止一本书与查询匹配,则更新第一本书。

    【讨论】:

      猜你喜欢
      • 2013-08-12
      • 2020-03-28
      • 2020-08-02
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2015-12-20
      • 2014-11-27
      • 2017-07-28
      相关资源
      最近更新 更多