skip to Main Content

I have the following Schema:

import Mongoose from 'mongoose'

const ThingSchema = new Mongoose.Schema({
  name: {
    type: String
  },

  traits: {
    type: Object
  }
})

const Thing = Mongoose.model('Thing', ThingSchema)

export default Thing

The first time I created such a document and saved it in the DB I set a name: 'something' and a traits: { propA: 1, propB: 2 } and everything was saved correctly.

Now I want to update the document and set a new property inside traits:

let thingInDB = await ThingModel.findOne({ name: 'something' })
console.log(thingInDB.traits) // <-- it logs { propA: 1, propB: 2 } as expected 
thingInDB.traits.propC = 3
await thingInDB.save()

The above code is executed with no errors but when I look in the DB the new propC is not saved in traits. I’ve tried multiple times.

Am I doing something wrong ?

2

Answers


  1. Chosen as BEST ANSWER

    I had to declare every property of the object explicitly:

    import Mongoose from 'mongoose'
    
    const ThingSchema = new Mongoose.Schema({
      name: {
        type: String
      },
    
      traits: {
        propA: {
          type: Number
        },
        propB: {
          type: Number
        },
        propC: {
          type: Number
        }
      }
    })
    
    const Thing = Mongoose.model('Thing', ThingSchema)
    
    export default Thing
    

  2. Have you tried using thingSchema.markModified("trait") before the .save() method? It worked for me when I ran into a similar problem in the past.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search