dmonaldo
dmonaldo

Reputation: 309

Update Nested Objects with Mongoose

I am trying to update nested objects with Mongoose. But when I receive the request, it looks like this:

{
'example[apple]': 'false',
'example[pear]': 'false',
'example[banana]': 'false',
'example[orange]': 'false',
}

My model looks like this:

email: {
    type: String,
    index:true,
    unique: true,
},
example: {
  apple: {type:Boolean, default: true},
  banana: {type:Boolean, default: true},
  pear: {type:Boolean, default: true},
  orange: {type:Boolean, default: true}
}

And the object I am sending looks like this:

var formData = {
  example: {
    apple: false,
    banana: false,
    pear: false,
    orange: false
  }
}

What am I doing wrong?

Upvotes: 0

Views: 526

Answers (1)

Elbassel
Elbassel

Reputation: 454

First of all, the request body { 'example[apple]': 'false', 'example[pear]': 'false', 'example[banana]': 'false', 'example[orange]': 'false', } is a JSON object you can access: example.apple and so on.
exampleObject must be JSON object first. From your model it seems example is attribute in the model so to update you have to options:
1- Is to update all documents by not providing the id of the document:
yourmodel.findAndUpdate({no thing here},exampleObject,callBack)
2-Is to update by condition;preferred: yourmodel.findAndUpdate(condition,exampleObject,callBack)
condition can be = {_id:an id}

Upvotes: 1

Related Questions