I have a User model, with a referenced child array of objects, I would like to find the User, and insert into the child referenced document, I don't want to update the child document, but rather insert another object into the reports document array.
Below is the User model, I basically want to find the User, and insert into Reports.
const User = mongoose.model(
"User",
new mongoose.Schema({
firstName: String,
lastName: String,
dateOfBirth: String,
email: String,
password: String,
agreedToTerms: Boolean,
agreementDate: String,
verified: Boolean,
roles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Role"
}
],
reports: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Reports"
}
]
})
);
Thank you!
CodePudding user response:
You can use findByIdAndUpdate
with $push
:
User.findByIdAndUpdate(<user-id>, {
$push: { reports: <report-id> }
});