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',
});
}
};