0
스키마몽구스/MongoDB의의 하위 문서 깊은 쿼리 및 업데이트
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})
,363,210
요구 사항
내가 (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)
}
})
나는 'F 챕터 '를 추가하기 위해 ailed 오류
그래서, 책의 하위 필드 중 하나를 얻으려면 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에서 가져 왔습니다.