mongoose 如何修复“.create不是一个函数”错误

dfddblmv  于 2023-01-13  发布在  Go
关注(0)|答案(2)|浏览(219)

我尝试初始化seed.js文件,以便在数据库中启动某些内容,但是当我运行node bin/seed.js时,总是得到'TypeError: Celebrity.create is not a function'
我试过重新安装mongoose npm包,我一直在寻找类似的问题,经过一段时间的寻找,我似乎一切正常,我找不到问题
下面是我的相关app.js代码

mongoose
    .connect('mongodb://localhost/cinema', { useNewUrlParser: true })
    .then(x => {
        console.log(`Connected to Mongo! Database name: "${x.connections[0].name}"`)
    })
    .catch(err => {
        console.error('Error connecting to mongo', err)
    })

这里是我的名人. model. js

const Schema = mongoose.Schema

const celebritySchema = new Schema(
    {
        name: String,
        occupation: String,
        catchPhrase: String
    },
    { timestamps: true }
)

const Celebrity = mongoose.model('Celebrity', celebritySchema)

module.exports = Celebrity

这是我的种子

const Celebrity = '../models/celebrity.model.js'

const dbName = 'cinema'
mongoose.connect(`mongodb://localhost/${dbName}`, { useNewUrlParser: true })

const celebrities = [
    {
        name: 'Alex',
        occupation: 'Parado',
        catchPhrase: 'Teo ayudameeee'
    }
]

Celebrity.create(celebrities, err => {
    if (err) {
        throw err
    }
    console.log(`Created ${celebrities.length} celebrities`)
    mongoose.connection.close()
})

这就是错误

Celebrity.create(celebrities, err => {
          ^

TypeError: Celebrity.create is not a function
    at Object.<anonymous> (/home/nacho/Ironhack/week4/day5/de/lab-mongoose-movies/starter-code/bin/seed.js:31:11)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
    at internal/main/run_main_module.js:21:11

我期望种子在我的数据库中创建1个值,但我得到了错误

svujldwt

svujldwt1#

您需要在种子文件中使用模型文件,如下所示:

const Celebrity = require('../models/celebrity.model.js');
6kkfgxo0

6kkfgxo02#

我今天遇到了同样的问题。解决方案是正确的导入。我在models/contact.js中有:模块.exports = {联系人,架构,};
并且在controllers/contacts.js中我更改了const Contact =需要(“../models/contact.js”);转换为常量{联系人} =要求(“../models/contact.js”);

相关问题