I’m looking to push this ObjectId from the Notes Schema: 635b70c1121186eefbbc5718
into the ‘notesId’ of this other Category Schema:
{
_id: new ObjectId("635b70c0121186eefbbc5714"),
name: 'frenchLessons',
creator: new ObjectId("635aa97815faaa052ae9cfce"),
notesId: [],
__v: 0
}
What I did was that I found the Category which holds both the name of the category in question and the Id of the current signed in user and tried push method but its not working:
.then(() => {
return Category.find({ name: categoryName, creator: creator });
})
.then((category) => {
category.notesId.push(note._id); //returns TypeError: Cannot read properties of undefined (reading 'push')
return category.save();
});
console.log(category)
returns me the correct document
2
Answers
Set a default
notesId
in case it was not defined.Also, you should use
findOne
if you want to retrieve a single object:Alternatively, you could add
default: []
to thenotesId
field in the schema declaration.This will help you to push _id directly to the array.