将文档插入mongo DB会导致错误

时间:2016-11-29 20:05:16

标签: node.js mongodb mongoose

我有一个节点js程序,我试图通过我的API向集合中插入一个新文档:

router.post('/add', function(req, res) {

    var apple = {
      name: req.body.name,
      ip: req.body.ip
    }

    serverSchema.insert(apple, function(err, result) {
      if (err) {
        console.log(err);
      } else {
        console.log('added');
      }
    });
});

架构如下所示:

var serverSchema = new mongoose.Schema({
  // unique + required do not allow duplicates in the dbs 
  name: {
    type: String,
    unique: true,
    required: true
  },
  ip: {
    type: String,
    unique: true,
    required: true
  }
});

module.exports = mongoose.model('serverSchema', serverSchema);

但是,当我尝试添加此项时,我会收到以下错误:

TypeError: Object function model(doc, fields, skipId) {
    if (!(this instanceof model)) {
      return new model(doc, fields, skipId);
    }
    Model.call(this, doc, fields, skipId);
  } has no method 'insert'

知道为什么会这样吗?

* dbs连接已打开

由于

1 个答案:

答案 0 :(得分:0)

您似乎错误地使用了serverSchemainsert没有mongoose.schema方法。

架构文件如下所示:

var mongoose = require("mongoose");

var db = mongoose.connect('mongodb://000.0.0.1/test');

var serverSchema = new mongoose.Schema({
   name: {
     type: String,
     unique: true,
     required: true
   },
   ip: {
     type: String,
     unique: true,
     required: true
   }
});

module.exports = db.model('server', serverSchema)

API文件如下所示:

router.post('/add', function(req, res) {

    //require mongoose model defines in model/serverSchema.js
    var aServer = require("./model/serverSchema");

    var apple = new aServer({name: "Honeycrisp", ip: "red"});

    post.save(function(err) {
      if (err) {
        return err;
      } else {
        console.log('added');
      }
    });
});