noDe1 noDe1 - 7 days ago 6
Node.js Question

Inserting document to mongo DB causes error

I have a node js program, and I am trying to insert a new document to the collection through my 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');
}
});
});


The schema looks like this:

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


However, when I try to add this item I get the following error thrown:

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'


Any idea why this is happening?

*The dbs connection is open

Thanks

Answer

It looks like you are using serverSchema incorrectly. There is no insert method for a mongoose.schema.

Schema file looks something like this:

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 file looks something like this:

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