如何使用mongoose / mongodb保存数据库中的数据?

时间:2017-05-10 13:30:39

标签: node.js mongodb express mongoose

我的代码由server.js文件组成,用于创建Node + Express服务器api。 server.js文件由我创建的模型和使用GETPOST方法的路由组成。

server.js

    var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var morgan = require('morgan');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var cors = require('cors');
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/contactlist');

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({type:'application/vnd.api+json'}));
app.use(methodOverride());
app.use(cors());


app.use(function(req,res,next){

    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Methods", "DELETE,PUT");
    res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With, Content-Type, Accept");
    next();
});

var contactSchema = mongoose.Schema({
    name:String,
    email:String,
    number:Number,
    address:String
});

var Contact = mongoose.model("Contact", contactSchema);


//Routers
//get
app.get('/contacts',function(req,res){
    console.log('inside get router fetching the contacts');

    Contact.find({},function(err, contacts){
        if(err)
        res.send(err);
        res.json(contacts);
    });

});

//post---->get

app.post('/contacts',function(req,res){
    console.log('creating the contacts');

    Contact.create({
        name:req.body.name,
        email:req.body.email,
        number:req.body.number,
        address:req.body.address,
        done: false
    },function(err,contact){
        if(err)
        res.send(err);

        Contact.find({},function(err,contact){
            if(err)
            res.send(err);
            res.json(contact);
        });
    });
});

app.listen(8080);
console.log('App listening on port 8080');

然后我创建了我的服务类,我从服务器获取数据。我没有任何问题。它工作得非常好。

然后是我的2页,在第一页中我创建了一个联系人列表,在第二页中我从服务器/ db获取该列表。

这就是为什么我无法从数据库中获取数据并发布正确的数据。数据库中发布的数据仅包含Id和-v标志。

logs

2 个答案:

答案 0 :(得分:2)

我要做的调试是设置mongoose调试选项

mongoose.set('debug',true)//启用日志记录收集方法+控制台的参数。

我怀疑你的模型架构没有正确定义。

日志输出可以帮助您了解未正确保存的原因。

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var mySchema = new Schema({
    // my props
});

mongoose.model('MyModel',mySchema); // mySchema是

在您致电mongoose.connect之后,您可以像这样使用您的模型

var BlogPost = mongoose.model('BlogPost');

答案 1 :(得分:0)

您忘记了查询对象:

Contact.find({}, function(err, contacts){
        if(err)
        res.send(err);
        res.json(contacts);
    });