【问题标题】:Mongoose TypeError: User is not a constructorMongoose TypeError:用户不是构造函数
【发布时间】:2017-04-08 02:01:33
【问题描述】:

我正在尝试使用 Mongoose 和 MongoDB 将子文档添加到父架构,但是我被抛出以下错误:

TypeError: User is not a constructor

这是基于 Mongoose 在 subdocuments 上的文档,我认为一切都是一样的。我该如何进一步调试?

路由器

// 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)
})

架构

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)

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    JavaScript 对变量名区分大小写。你有User 模型和User 结果同名。

    您的代码将适用于以下更改:

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

    还请记住,在您的代码中,您将声明另一个名为 user 的变量。您需要将其更改为不同的内容。

    【讨论】:

    • 我遇到了同样的问题。您的解决方案解决了我的问题。感谢分享
    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 2017-03-09
    • 2019-05-09
    • 2017-08-02
    • 2019-08-14
    • 2021-02-06
    相关资源
    最近更新 更多