如何修复猫鼬中的``.create不是函数''错误

时间:2019-07-27 09:11:27

标签: javascript mongoose

我正在尝试初始化seed.js文件以在数据库中启动某些内容,但是当我运行“ node bin / seed.js”时,我不断收到“ TypeError:Celebrity.create不是函数”

我尝试重新安装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)
    })

这是我的celebrity.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

这是我的seed.js

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个值,但出现错误

1 个答案:

答案 0 :(得分:1)

您需要像这样在种子文件中要求模型文件:

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