Mongoose 类型错误:User 不是一个构造函数。

6
我正在尝试使用Mongoose和MongoDB向父模式添加子文档,但是我遇到了以下错误:
TypeError: User is not a constructor

这是基于Mongoose有关子文档的文档,我认为一切都是相同的。我该如何进一步调试?
路由器
// 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)
1个回答

7

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

只需进行以下更改,您的代码即可正常工作:

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

/* rest of your code */

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

2
我遇到了同样的问题。你的解决方案解决了我的问题。 谢谢分享。 - AllJs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接