Nacho Alonso
Nacho Alonso

Reputation: 45

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

Upvotes: 4

Views: 10936

Answers (3)

Ripka Victoriia
Ripka Victoriia

Reputation: 1

The solution is in the correct import.

In models/contact.js, I have:

module.exports = {
  Contact,
  schemas,
};

And in controllers/contacts.js, I changed:

const Contact = require("../models/contact.js"); 

into:

const { Contact } = require("../models/contact.js");

Upvotes: 0

kim pax
kim pax

Reputation: 1

Ensure you are exporting the schema as a model.

Upvotes: 0

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You need to require the model file in your seed file like this:

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

Upvotes: 3

Related Questions