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',
});
}
};
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.