我想将数据添加到我的mongodb集合名称是'post', 这是我的server.js代码
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
Post = require('./www/js/models/post.js');
mongoose.connect('mongodb://localhost/BlogDB'); //connect to mongoose
var db = mongoose.connection;
app.post('/api/post',function (req, res) {
var post = req.body;
Post.addPost(post,function (error, post) {
if(error){
throw error;
}
res.json(post);
})
});
这是我的帖子架构 -
var mongoose = require('mongoose');
/// Post schema
var postSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String
},
author: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
}, {collection: 'post'});
var Post = module.exports = mongoose.model('Post', postSchema);
//add post
module.exports.addPost = function (post, callback) {
Post.create(post,callback);
};
当我从RestEasy chrome扩展发送帖子请求然后抛出此错误消息
throw er; // Unhandled 'error' event
^
ValidationError: Post validation failed
at MongooseError.ValidationError (F:\Project\Private\Blog\node_modules\mongoose\lib\error\validation.js:23:11)
at model.Document.invalidate (F:\Project\Private\Blog\node_modules\mongoose\lib\document.js:1501:32)
at F:\Project\Private\Blog\node_modules\mongoose\lib\document.js:1377:17
at validate (F:\Project\Private\Blog\node_modules\mongoose\lib\schematype.js:705:7)
at F:\Project\Private\Blog\node_modules\mongoose\lib\schematype.js:742:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (F:\Project\Private\Blog\node_modules\mongoose\lib\schematype.js:710:19)
at F:\Project\Private\Blog\node_modules\mongoose\lib\document.js:1375:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
[nodemon] app crashed - waiting for file changes before starting...
答案 0 :(得分:0)
ValidationError:发布验证失败
Mongoose告诉您,您在Mongo中插入的数据无效,因为它不满足您构建的架构。因此,请仔细检查您要插入的内容。
答案 1 :(得分:0)
似乎来自Mongoose的帖子数据JSON的架构验证错误。
{
"title": "Javascript",
"description": "Javascript story",
"author": "Karthikeyan.A",
"date:: "Tue Apr 04 2017 13:56:23 GMT+0530 (IST)"
}