Mongoose类型错误:Rental不是构造函数
我对后端开发非常陌生,尝试导入Mongoose模型并使用它来编写,然后从数据库中读取。如果我导入模型并尝试使用它,我会得到一个错误,即它不是构造函数:Mongoose类型错误:Rental不是构造函数,mongoose,typeerror,Mongoose,Typeerror,我对后端开发非常陌生,尝试导入Mongoose模型并使用它来编写,然后从数据库中读取。如果我导入模型并尝试使用它,我会得到一个错误,即它不是构造函数: UnhandledPromiseRejectionWarning: TypeError: Rental is not a constructor 如果我将模型复制到索引文件中,它可以正常工作 我在这里看到了一些类似的问题。其中大多数导出的是模式,而不是模型。我正在尝试使用模型,并且模型和实例之间的大小写是正确的 模型: const mongoo
UnhandledPromiseRejectionWarning: TypeError: Rental is not a constructor
如果我将模型复制到索引文件中,它可以正常工作
我在这里看到了一些类似的问题。其中大多数导出的是模式,而不是模型。我正在尝试使用模型,并且模型和实例之间的大小写是正确的
模型:
const mongoose = require('mongoose')
const Joi = require('@hapi/joi')
const rentalSchema = new mongoose.Schema({
customer: {
type: new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 5
},
isGold: {
type: Boolean,
default: false
},
phone: {
type: String,
required: true,
minlength: 5,
maxlength: 50
}
}),
required: true
},
movie: {
type: new mongoose.Schema({
title: {
type: String,
required: true,
trim: true,
minlength: 5,
maxlength: 255
},
dailyRentalRate: {
type: Number,
required: true,
min: 0,
max: 255
}
}),
required: true
},
dateOut: {
type: Date,
required: true,
default: Date.now
},
dateReturned: {
type: Date
},
rentalFee: {
type: Number,
min: 0
}
})
const Rental = mongoose.model('Rental', rentalSchema)
//...
module.exports = { Rental, validateObject }
索引文件:
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test', () => {
console.log('Connected to Mongodb')
})
const Rental = require('./models/rental')
const customerId = mongoose.Types.ObjectId()
const movieId = mongoose.Types.ObjectId()
async function createRental() {
const rental = new Rental({
customer: {
_id: customerId,
name: '12345',
phone: '12345'
},
movie: {
_id: movieId,
title: '12345',
dailyRentalRate: 2
}
})
await rental.save()
console.log(rental)
}
async function getRental() {
const rentalInDb = await Rental.findOne({
'customer._id': customerId,
'movie._id': movieId
})
console.log(rentalInDb)
}
createRental()
getRental()
我希望有两个控制台日志,但我得到的却是一个typeerror。为什么这不起作用?当您像这样导出模型时:
module.exports = { Rental, validateObject }
您需要以以下方式进行要求:
const { Rental } = require('./models/rental')
按以下方式导出模型时:
module.exports = { Rental, validateObject }
您需要以以下方式进行要求:
const { Rental } = require('./models/rental')
我真不敢相信我错过了。谢谢我真不敢相信我错过了。谢谢