1

errmsg: 'The field \'weight\' must be an array but is of type int in document

My Schema:

weight: [{
  type: Number
}]

and my post request:

app.post('/edit', function(req, res){
    var update = {  $push: {"weight": req.body.weight}};
    User.findOneAndUpdate(conditions, update, options, function (err)
    {
      if (err)
      {
          console.log(err);
      }
      else
      {
          console.log('yep');
      }
    })
});
Elena
  • 569
  • 3
  • 7
  • 19
  • Looks like your field is something like `{"weight": 3}` in db and you're using `$push` to push array value into `int` type field. – s7vr Apr 07 '17 at 16:13
  • So, I should change the schema to smth like: weight: [{ type: Array }], ? it doesn't work – Elena Apr 07 '17 at 16:23
  • No, the schema definition is correct. I meant to suggest that you've to fix the data in the `weight` field first. It should look like `{"weight": [3]}` in db and you can use the update with `$push` to add more values into array. So you possibly need like a update script to change the data first. See if this answer help. http://stackoverflow.com/questions/7401394/mongodb-type-change-to-array – s7vr Apr 07 '17 at 16:27

2 Answers2

0

If there are multiple documents in the collection that match your conditions, you can update only suitable one by adding { weight: { $type: 4 } } to your conditions.

Otherwise your application's schema doesn't match data in the database.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75
-1

This might work.

//Schema

weight: [Number]

http://mongoosejs.com/docs/schematypes.html

//Or this way too if pushing objects into array

//Schema

weight: [{
  weight: {
    type: Number
  }
}]

//Then in API

var update = {  $push: {"weight": { "weight": req.body.weight }}};
henhen
  • 1,038
  • 3
  • 18
  • 36