猫鼬TypeError:Rental不是构造函数

时间:2019-08-04 14:29:27

标签: mongoose typeerror

对于后端开发,我很陌生,尝试导入Mongoose模型并使用它进行编写,然后从数据库中读取。如果导入模型并尝试使用它,则会收到错误消息,它不是构造函数:

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。为什么这行不通?

1 个答案:

答案 0 :(得分:0)

当您像这样导出模型时:

module.exports = { Rental, validateObject }

您需要以这种方式要求它:

const { Rental } = require('./models/rental')