0

Let's say I have a Schema that looks like this:

const Schema1 = new Schema({
  field1: String,
  field2: String,
  array1: [{
    objfield1: String
    objfield2: Date,
    objfield3: {
      type: Schema.Types.ObjectId,
      ref: 'OtherModel',
      required: true,
    },
  }],
}, options);

Here array1 is an array of objects. I want to be able to hit an endpoint with a PUT request and push a new object into the array1 array. I have tried using _.merge from lodash, I have tried using push to add the new object into the array, but to no avail.

exports.addObject = async (req, res, next) => {
  try {

    let schemaInstance = await db.Schema1.findById(req.params.id);
    schemaInstance['array1'].push(req.body)
    schemaInstance.markModified('array1');
    let updatedSchemaInstance = await schemaInstance.save();

    return res.status('200').json(updatedSchemaInstance);

  } catch (err) {
    console.log(err);
    return next({
      status: 400,
      message: 'No users in the database',
    });
  }
};
1
  • do you get any err from the try..catch? Commented Mar 2, 2020 at 20:52

1 Answer 1

2

if you want update your array with new element, use findOneAndUpdate() function and $push

like:

exports.addObject = async (req, res, next) => {
  try {

    let schemaInstance = await db.Schema1.findOneAndUpdate(
      {_id: req.params.id}, 
      {$push: {'array1': req.body});
    schemaInstance.markModified('array1');
    let updatedSchemaInstance = await schemaInstance.save();

    return res.status('200').json(updatedSchemaInstance);

  } catch (err) {
    console.log(err);
    return next({
      status: 400,
      message: 'No users in the database',
    });
  }
};

mongoose findOneAndUpdate() : https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate mongo $push : https://docs.mongodb.com/manual/reference/operator/update/push/

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

1 Comment

Thanks! This worked, with the caveat that the option {new: true} is needed to return the updated record.

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.