My schema looks like this ...
{
name: String,
email: {
type: String,
required: true,
index: true,
},
age: {
type: Number,
default: 18,
required: false,
minlength: [2, 'Too short'],
maxlength: [2, 'Too long'],
},
role: {
type: String,
default: 'client',
},
address: String,
answers: [answerSchema],
}
const answerSchema = new Schema({
position: Number,
slider: Number,
scale: Number,
})
The userId is known. How do I add values to the user.answers array?
I've tried ...
const updated = await User.findByIdAndUpdate(
{ _id: req.params.id },
{ $set: {answers}},
{ new: true }
)
as well as $push ... just I just on't know how to do this.
First thing: You have to declare answerSchema before the main schema because it thrown the error:
ReferenceError: Cannot access 'answerSchema' before initialization
So your code has to be:
const answerSchema = new Schema({ ... }) // First
const mainSchema = new Schema({ ... }) // Second
Then, into the query, if you use findByIdAndUpdate you can use the _id directly in the first parameter. Also you can use $push to add a new object, like this:
const updated = await User.findByIdAndUpdate(
req.params.id,
{ $push: {
answers:{
/* your object to insert here*/
}
}},
{ new: true }
)
There is an example how $push works here