Home > Software design >  Mongoose will not update document with new object property
Mongoose will not update document with new object property

Time:04-16

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 ?

CodePudding user response:

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

CodePudding user response:

Have you tried using thingSchema.markModified("trait") before the .save() method, it worked for me when I rank into a similar problem in the past

  • Related