Kawd
Kawd

Reputation: 4450

Mongoose will not update document with new object property

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 ?

Upvotes: 0

Views: 1042

Answers (2)

Johan511
Johan511

Reputation: 11

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.

Upvotes: 1

Kawd
Kawd

Reputation: 4450

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

Upvotes: 0

Related Questions