[英]How to save the data in the database using mongoose/mongodb?
我的代码包含用于创建Node + Express服务器api的server.js
文件。 server.js文件由我创建的模型以及带有GET
和POST
方法的路由组成。
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标志。
我要做的调试是设置猫鼬调试选项
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');
您忘记了查询对象:
Contact.find({}, function(err, contacts){
if(err)
res.send(err);
res.json(contacts);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.