0

Schema

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

Sample object (person object)

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

Subdocument (chapter object)

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

Requirement

I would want to add the chapter object into the sample object (person.books)

Expected

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

Tried

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

I got 'Failed to add chapter' error

So, I tried to findOne to get any of fields in books subdocument.

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

It gave me the following result,

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

But, I was expecting only author here.

Eventually, I would like to know how to insert an object into subdocument in Mongodb/Mongoose.

P.S: new Date() I got from express.js, which does not matter here though.

Prakash Ramasamy
  • 385
  • 1
  • 7
  • 15

1 Answers1

2

This can help you:

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

Remember though that if more than one book matches the query, the first one is updated.

cbartosiak
  • 785
  • 6
  • 11