skip to Main Content

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


  1. Set a default notesId in case it was not defined.
    Also, you should use findOne if you want to retrieve a single object:

    Category.findOne(
        { name: categoryName, creator: creator },
        async (err, category) => {
          if (category.notesId === undefined) category.notesId = [];
          category.notesId.push(note._id);
          await category.save();
        }
      );
    

    Alternatively, you could add default: [] to the notesId field in the schema declaration.

    Login or Signup to reply.
  2. This will help you to push _id directly to the array.

      let data=await Category.findOneAndUpdate({ name: categoryName, creator: creator }, {
        $push: { notesId : note._id},
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search