我正在使用 Mongoose 创建一个架构,并尝试通过 Postman 将数据添加到 mongoDB,它正在向数据库添加空数据。我假设我的问题是数据从浏览器解析到服务器的方式,这是我的 app.js 设置。
添加到数据库的内容
{ "_id" : ObjectId("57846282c7b5f51d4c1742a9"), "__v" : 0 }
这是 app.js 文件
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var routes = require('./routes/index');
var mongoose = require('mongoose');
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/growlingRabbit');
var Page = require('./models/growling_rabbit_page_text.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userPhoto');
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.post('/api/text',function(req,res){
var text = new Page();
text.name = req.body.name;
text.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Text Added!' });
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
这是模型
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var pageSchema = new Schema({
homePage: String,
communityPage: String,
eventPage: String,
contactPage: String,
galleryPage: String });
module.exports = mongoose.model('Page', pageSchema);;
救命,我确信这是非常明显的事情,不幸的是我找不到它。
最佳答案
那么你用
创建一个页面
var text = new Page();
text.name = req.body.name;
但是您的架构没有 name
属性。
像这样更改您的架构:
var pageSchema = new Schema({
name: String,
homePage: String,
communityPage: String,
eventPage: String,
contactPage: String,
galleryPage: String });
<小时/>
另一个问题可能是使用了错误的选项通过 Postman 发布数据。
确保在测试 Node API 时使用 x-www-form-urlencoded
关于javascript - 无法将数据添加到 mongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38319562/