【问题标题】:TypeError: Post.create is not a function for mongodbTypeError: Post.create 不是 mongodb 的函数
【发布时间】:2019-08-05 16:47:41
【问题描述】:

test.js 文件包含.create 函数,该函数在运行时显示类型错误。 我尝试过插入函数保存函数,但它根本没有将其识别为函数。我在 create 函数中找不到类型错误。

test.js 文件

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 文件

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

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

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

module.exports = Post

【问题讨论】:

  • 你应该在 test.js 中包含 Post Modal 并使用它。如果是 const Post = require('/database/models/Post') ?
  • 你能edit你的问题并在那里发布完整的错误信息吗?

标签: javascript html node.js mongodb


【解决方案1】:

在导入架构时必须指明对象。试试这个。

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

【讨论】:

    【解决方案2】:

    我会这样做

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

    如果您有很多模型,您可能想要创建一个不同的文件,并将所有模型放在一起并需要这个新文件

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

    然后在你的 test.js 文件中

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

    【讨论】:

      【解决方案3】:

      使用为 mongodb 定义模式路径

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-29
        • 2020-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多