无法使用mongoose插入数据

时间:2016-10-20 10:08:22

标签: node.js mongodb mongoose mean-stack crud

我是新的平均堆栈我完成了更新,删除和获取数据,但无法在mongoose中插入数据,任何人都可以帮助我。谢谢以下是我的代码。

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

当错误显示

时,此时插入数据

Test处的未定义类型name   你尝试过嵌套Schemas吗?您只能使用refs或数组进行嵌套。     在Function.Schema.interpretAsType(/usr/lib/node_modules/mongoose/lib/schema.js:666:11)     在Schema.path(/usr/lib/node_modules/mongoose/lib/schema.js:545:29)     在Schema.add(/usr/lib/node_modules/mongoose/lib/schema.js:429:12)     在新架构(/usr/lib/node_modules/mongoose/lib/schema.js:100:10)     at /var/www/html/contactlistappmvc/server.js:53:25

1 个答案:

答案 0 :(得分:0)

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

您应该保存模型,而不是模式。你在这里做的是将一个对象传递给模式。文档是模型的实例,而不是模式。模式只是一个对象定义。

而不是你在这里做了什么,为什么不做呢

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


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

然后执行contactModel.save()