【发布时间】: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