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');
      }
    })
});
3
  • Looks like your field is something like {"weight": 3} in db and you're using $push to push array value into int type field. Commented Apr 7, 2017 at 16:13
  • So, I should change the schema to smth like: weight: [{ type: Array }], ? it doesn't work Commented Apr 7, 2017 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. stackoverflow.com/questions/7401394/… Commented Apr 7, 2017 at 16:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I use a user_id as a condition, so I have only one record
Then it falls into 'otherwise' part of the answer.
-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 }}};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.