![](/img/trans.png)
[英]How to process deep update with subdocument in Mongodb/Mongoose?
[英]mongoose/mongodb subdocument deep query and update
架構
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})
需求
我想將Chapter對象添加到示例對象(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來獲取books子文檔中的任何字段。
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中將對象插入子文檔中。
PS:我從express.js獲得了新的Date(),但這在這里無關緊要。
這可以幫助您:
db.yourDb.update(
{
"_id": 1,
"books": {
"$elemMatch": {
"date": {
"$lte": ISODate("2017-10-24T20:01:18.362+0000")
}
}
}
},
{
"$set": {
"books.$.chapter": { "_id": 1, "completed": true }
}
}
)
但是請記住,如果與該查詢匹配的書不止一本,則將更新第一本書。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.