sunil sunil - 1 month ago 5
Node.js Question

can't insert data using mongoose

i am new in mean stack i completed update,delete,and get data but can't insert data in mongoose can anyone help me please.thanks in advance below is my code.

var express = require('express');
var mongojs = require('mongojs');
var db = require('mongoose');
var bodyParser = require('body-parser');

var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
db.connect('mongodb://localhost/contactlist');
var db1 = db.connection;
db1.on('error', err);
db1.once('open',startserver);
function err(){
console.log('connection error:');
}
function startserver(){
console.log('start');
app.listen(3000);
}
var contactdetails1 = new db.Schema({
name:String,
email:String,
password:String,
number:String
});
db1.model('Contactdetails',contactdetails1);

app.post('/contactList',function(req,res){
console.log("Get insert request"+req.body);
//var contactList = new ContactList(req.body);
var contactdetails1 = new db.Schema({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number
});


contactdetails1.save(function(err,data) {
if (err) {
response = {
"status":0,
"error":err,
};
}else{
response = {
"status":1,
"data":data,
"message":"User registered successfully"
};
}
console.log(response);
res.json(response);
});
});


when inserting data at that time below error show

Undefined type
Test
at
name

Did you try nesting Schemas? You can only nest using refs or arrays.
at Function.Schema.interpretAsType (/usr/lib/node_modules/mongoose/lib/schema.js:666:11)
at Schema.path (/usr/lib/node_modules/mongoose/lib/schema.js:545:29)
at Schema.add (/usr/lib/node_modules/mongoose/lib/schema.js:429:12)
at new Schema (/usr/lib/node_modules/mongoose/lib/schema.js:100:10)
at /var/www/html/contactlistappmvc/server.js:53:25

Answer
var contactdetails1 = new db.Schema({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number        
});

You should be saving a model, not a schema. What you've done here is pass an object to the schema. Documents are instances of Models, not schemas. A schema is just an object definition.

Instead of what you've done here, why don't you do

var ContactModel = mongoose.model('Contactdetails',contactdetails1);


var contactModel = new ContactModel({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number 
})

And then do a contactModel.save()