Mongoose $push add to document

Ravil Source

I'm trying to add an element to an existing array, but it produces an error:

The field 'data' must be an array but is of type object in document 

Scheme:

const testScheme = new Schema({
  user: {
    type: String,
    required: true
  },
  data: [{
    platform: {
      type: String,
      required: true
    },
    item_name: {
      type: String,
      required: true
    },
    price: {
      type: Number,
      default: 0
    },
    updatedAt: Date
  }]
}, {
  versionKey: false,
  timestamps: true
});

Document in mongodb:

"data": [{
        "price": 50,
        "_id": "5a84268d6c78a60c10479437",
        "platform": "pl1",
        "item_name": "test"
    }],
    "_id": "5a841bccb44cb8cd5b974d71",
    "user": "Ivan",
    "updatedAt": "2018-02-14T12:07:41.793Z",
    "createdAt": "2018-02-14T11:21:48.104Z"

Query:

var item = {
    "platform": "pl700",
    "item_name": "someText",
    "price": 700,
    "updatedAt": new Date()
  };
  Data.findOneAndUpdate({
      'user': 'Ivan'
    }, {
      $push: {
        'data': item
      }
    }, {
      safe: true,
      upsert: true
    },
    function(err, data) {
      if (err) return res.status(500).send({
        'error': err
      });
      res.status(200).send({
        'data': data
      });
    }
  );

I trying query with $set parametr and it works, but $push, $addToSet didn't work for me. Also i tried to google this problem and can't solve it.

mongodbmongoose

Answers

answered 6 months ago Veeram #1

It is not clear what you are intending to do.

To push an item into array you use $addToSet/$push. For updating a array you use $set.

Using $set you can update the whole document or you can update the specific field.

Update whole doc

Data.findOneAndUpdate({
      'user': 'Ivan',
      'data._id':item._id
    }, {
      $set: {
        'data.$': item
      }
    }...
)

Update specific field

Data.findOneAndUpdate({
       'user': 'Ivan',
       'data._id':item._id
     }, {
       $set: {
       'data.$.price': item.price
       }
    }...
)

comments powered by Disqus