ashir kulshreshtha
ashir kulshreshtha

Reputation: 11

TypeError: Post.create is not a function for mongodb

test.js file contains .create function which on running shows the type error. I have tried insert function save function but it does not identify it as a function at all. I cannot find out what is the type error here in create function.

test.js file

const mongoose = require('mongoose')
const Post = ('/database/models/Post')

mongoose.connect('mongodb://localhost/nodejs-test-blog')

// Post.find({}, (error, posts) => {
//     console.log(error, posts)
//   })

Post.create({
  title: 'My second blog post',
  description: 'Second Blog post description',
  content: 'Second Lorem ipsum content.'
}, (error, post) => {
  console.log(error, post)
})

Post.js file

const mongoose = require('mongoose')
///

const PostSchema = new mongoose.Schema({
  title: String,
  description: String,
  content: String
})

const Post = mongoose.model('Post', PostSchema)

module.exports = Post

Upvotes: 0

Views: 2713

Answers (3)

Alagarasan M
Alagarasan M

Reputation: 907

The object must be denoted while importing the schema. Try this.

const Post = ('/database/models/Post').Post;

Upvotes: 0

I would do it like this

require('./database/models/Post');
const mongoose = require('mongoose');
const Post = mongoose.model('Post);

and if you have a lot of models you might want to create a different file and require all the models together and require this new file

models.js

const glob = require('glob');
const path = require('path');

// grab all mongo models name to require them
glob.sync('./database/models/**/*.js').forEach(file => {
    require(path.resolve(file));
});

and then in your test.js file

require('./path/to/models.js');
const mongoose = require('mongoose');
const Post = mongoose.model('Post);

Upvotes: 0

Use defining schema path for mongodb

require('./database/models/Post')

Upvotes: 1

Related Questions