javascript - 如何修复 Mongoose 中的 '.create is not a function' 错误

标签 javascript mongoose

我正在尝试初始化一个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

这是我的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 个值,但我得到了错误

最佳答案

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

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

关于javascript - 如何修复 Mongoose 中的 '.create is not a function' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57230731/

相关文章:

MongoDB 一对多 - 子模型上的 ID 数组或 ID 引用?

c# - Mongodb聚合组性能

node.js - Mongoose 模式更新 GeoJSON

node.js - 聚合并展平 MongoDB 中的数组字段

javascript - 截至2018年支持ES6(ECMAScript 2015)

javascript - 在 node.js 中处理 PromiseRejection

javascript - TinyMCE - 允许表格单元格元素作为有效的 html

javascript - 我在这个随机数生成器中缺少什么

javascript - 拖动行时自动滚动表格

MongoDB $lookup 与 $match 和 $eq,匹配对象数组内的值