mongoose - blogPost不是构造函数错误(架构/模型错误)

时间:2017-08-21 14:38:52

标签: node.js mongoose schema

我是mongoose和mongodb的新手,我正在尝试连接到mlab并插入一些数据,但我不断收到以下代码的错误

var newPost = new blogPost({title:'First Post', post:'this is my first post'});
              ^

TypeError: blogPost is not a constructor
    at Object.<anonymous> (C:\Users\ipingou\website\hwnay\index2.js:39:15)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

这是我的代码:

const mongoose = require('mongoose');    

var blogPost = mongoose.Schema({
        title : String,
        post : String
    });

mongoose.model('blogPost',blogPost, 'blogPost');

var newPost = new blogPost({title:'First Post', post:'this is my first post'});

newPost.save(function(err,newPost){
    if(err) return console.log(err);
    console.log(newPost);
});

1 个答案:

答案 0 :(得分:1)

你错过了一个关键部分。所以你已经定义了一个模式,但是你需要从该模式创建一个模型:

var Post = mongoose.model('blogPost', blogPost);

var newPost = new Post({ title: 'First Post', post: 'this is my first post' });

newPost.save(function(err, newPost){
    if(err) {
      return console.log(err);
    }
    console.log(newPost);
});

您可以找到示例here。可以找到更详细的解释here