简体   繁体   中英

How to fix '.create is not a function' error in mongoose

I am trying to initialize a seed.js file to have something to start in my database but when I run node bin/seed.js I keep getting 'TypeError: Celebrity.create is not a function'

I have tried reinstalling mongoose npm package, I have been looking for similar problems and after some time looking it seems to me that everything is OK and I can't find the problem

Here is my relevant app.js code

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)
    })

here is my 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

here is my 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()
})

and this is the error

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

I expected the seed to create 1 value in my data base but i get the error

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

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

I had the same problem today. The solution was in the correct import. I have in models/contact.js: module.exports = { Contact, schemas, };

And in controllers/contacts.js I changed const Contact = require("../models/contact.js"); into const { Contact } = require("../models/contact.js");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM