Mongoose TypeError: User is not a constructor
Asked Answered
R

2

6

I'm trying to add a subdocument to a parent schema with Mongoose and MongoDB however I'm being thrown the following error:

TypeError: User is not a constructor

This is based off Mongoose's documentation on subdocuments and I think everything is the same. How can I debug this further?

Router

// Add a destination to the DB
router.post('/add', function(req, res, next) {
  let airport = req.body.destination
  let month = req.body.month
  let id = (req.user.id)

  User.findById(id , function (err, User) {
    if (err) return handleError(err)

    function addToCart (airport, month, id) {
      var user = new User ({
        destinations: [(
          airport = '',
          month = ''
        )]
      })

      dog.destinations[0].airport = airport
      dog.destinations[0].month = month
      dog.save(callback)
      res.status(200).send('added')
    }
    addToCart()
  })
  console.log(airport)
})

Schema

var destinationSchema = new Schema({
  airport: String,
  month: String
})

// Define the scheme
var User = new Schema ({
  firstName: {
    type: String,
    index: true
  },
  lastName: {
    type: String,
    index: true
  },
  email: {
    type: String,
    index: true
  },
  homeAirport: {
    type: String,
    index: true
  },
  destinations: [destinationSchema]
})


User.plugin(passportLocalMongoose)

module.exports = mongoose.model('User', User)
Robbi answered 23/11, 2016 at 22:11 Comment(0)
F
7

JavaScript is case sensitive about the variable names. You have User model and the User result with the same name.

Your code will work with the following change :

   User.findById(id , function (err, user) {
/*                                   ^ use small `u` */
       if (err) return handleError(err)

/* rest of your code */

Also keep in mind that further in your code you are declaring another variable named user. You will need to change that to something different.

Freebooter answered 23/11, 2016 at 22:17 Comment(1)
I had the same issue. Your solution solved my problem. Thanks for sharingEleen
A
0

Make sure your 'User' collection is imported as const {User} = require('file-path'), but not simply as const User = require('file-path'), into your user.js (or any file you want to import User)

Argol answered 3/6 at 5:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.