Home > Mobile >  Mongoose Trouble Adding Subdocs to Array
Mongoose Trouble Adding Subdocs to Array

Time:01-11

I am looking to push to an array on my users schema in mongoose. I am following mongoose's Adding Subdocs to Arrays documentation but keep getting an error on user.notes.push(newNotebook)

TypeError: Cannot read properties of undefined (reading 'push')

Here is my setup:

const User = require('../models/userModel')


const addNotebook = async (req, res) => {

...

const user = User.find({ userId })

const newNotebook = { userId: userId, notebookId: notebookId, title: title, numNotes: 0 }

user.notebooks.push(newNotebook)
        
}

Any help would be much appreciated.

CodePudding user response:

It would be like this:

const addNotebook = async(req, res) => {

  const user = await User.find({
    userId
  }).limit(1).exec()

  if (!user) return

  const newNotebook = {
    userId: userId,
    notebookId: notebookId,
    title: title,
    numNotes: 0
  }

  user.notebooks.push(newNotebook)
  await user.save()
}

CodePudding user response:

This is probably caused because "notebooks" is undefined by default for your userModel/schema

You can resolve this by two methods

const User = require('../models/userModel')


const addNotebook = async(req, res) => {

  ...

  const user = User.find({
    userId
  })

  const newNotebook = {
    userId: userId,
    notebookId: notebookId,
    title: title,
    numNotes: 0
  }
  user.notebooks = user.notebooks || []; // returns user.notebooks if defined else empty array
  user.notebooks.push(newNotebook)

}

RECOMMENDED Or you can set default value for notebooks in your userModel like this (might not update your existing user documents) How to set default value in schema mongoose?

  • Related