Mongoose嵌套模式验证错误

时间:2016-09-15 01:34:04

标签: mongoose-schema

我对MEAN堆栈相当新,所以也许我正在做一些非常愚蠢的事情。

我有几个定义的模式(BlogEntry,ForumPost),它们都需要相同的嵌套模式(在本例中为Comment),所以我已将Comment模式移动到它自己的文件中,以避免任何代码重复。

仅看一下BlogEntry的例子,我在blog.js模型中有以下内容:

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

var BlogEntry = new Schema({
    title: String,
    thumbnailUrl: String,
    content: String,
    comments: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ]
}, {
    timestamps: true
});


var Blog = new Schema({
    createdBy: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    name: {
        type: String,
        required: true
    },
    headerImageUrl: String,
    description: String,
    blogEntries: [BlogEntry]
}, {
    timestamps: true
});

module.exports = mongoose.model('Blog', Blog);

并且Comment架构包含在comment.js中:

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

var Comment = new Schema({
    commentText:  {
        type: String,
        required: true
    },
    postedBy:  {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    parentComment: {
        type: Schema.Types.ObjectId,
        ref: 'Comment'
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('Comment', Comment);

我处理博客信息的路由器包含以下内容:

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Blog = require('../models/blog');
var Verify = require('./verify');
var blogRouter = express.Router();
blogRouter.use(bodyParser.json());

blogRouter.route('/')
.get(function(req, res, next) {
    Blog.find(req.query) 
        .populate('createdBy')
        .exec(function(err, blog) {
            if(err) return next(err);
            res.json(blog);
        });
})

.post(Verify.verifyOrdinaryUser, function(req, res, next) {
    req.body.createdBy = req.decoded._id;
    Blog.create(req.body, function(err, blog) {
        if(err) return next(err);
        console.log("Blog created");
        var id = blog._id;
        res.writeHead(200, { 'Content-Type': 'text/plain'});
        res.end('Added the blog with id: ' + id);
    });
});

module.exports = blogRouter;

当Comments模式位于单独的文件中,并且我发布了以下请求时,我收到验证错误:

{
    "name": "A Cheesemaker's Adventure",
    "headerImageUrl": "images/cheeseAdven.png",
    "description": "The story of a man's transformation from a miserable, downtrodden software engineer to a bouyant, joy-filled cheesemaker.",
    "blogEntries" : [
        {
          "title": "I like cheese",
          "content": "Here is my story...blah blah blah...",
          "comments": [
              {
                 "commentText": "Who's is this guy kidding!"
              }
          ]
        }
    ]
}


<!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Blog validation failed</h1><h2></h2><pre>ValidationError: Blog validation failed
    at MongooseError.ValidationError (C:\Development\hcj-express\node_modules\mongoose\lib\error\validation.js:22:11)
    at model.Document.invalidate (C:\Development\hcj-express\node_modules\mongoose\lib\document.js:1410:32)
    at EmbeddedDocument.invalidate (C:\Development\hcj-express\node_modules\mongoose\lib\types\embedded.js:190:19)
    at EmbeddedDocument.Document.set (C:\Development\hcj-express\node_modules\mongoose\lib\document.js:703:10)
    at EmbeddedDocument.Document.set (C:\Development\hcj-express\node_modules\mongoose\lib\document.js:548:18)
    at EmbeddedDocument.Document (C:\Development\hcj-express\node_modules\mongoose\lib\document.js:67:10)
    at new EmbeddedDocument (C:\Development\hcj-express\node_modules\mongoose\lib\types\embedded.js:30:12)
    at EmbeddedDocument (C:\Development\hcj-express\node_modules\mongoose\lib\schema\documentarray.js:27:17)
    at DocumentArray.cast (C:\Development\hcj-express\node_modules\mongoose\lib\schema\documentarray.js:254:22)
    at DocumentArray.SchemaType.applySetters (C:\Development\hcj-express\node_modules\mongoose\lib\schematype.js:628:12)
    at model.Document.set (C:\Development\hcj-express\node_modules\mongoose\lib\document.js:695:18)
    at model.Document.set (C:\Development\hcj-express\node_modules\mongoose\lib\document.js:548:18)
    at model.Document (C:\Development\hcj-express\node_modules\mongoose\lib\document.js:67:10)
    at model.Model (C:\Development\hcj-express\node_modules\mongoose\lib\model.js:41:12)
    at new model (C:\Development\hcj-express\node_modules\mongoose\lib\model.js:3175:11)
    at C:\Development\hcj-express\node_modules\mongoose\lib\model.js:1847:51</pre></body></html>

但是,如果我删除了comment.js文件,并将Comment模式移动到blog.js文件中,就像这样,我可以发布与上面列出的完全相同的消息,验证错误就消失了,我成功发布数据。

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

var Comment = new Schema({
    commentText:  {
        type: String,
        required: true
    },
    postedBy:  {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    parentComment: {
        type: Schema.Types.ObjectId,
        ref: 'Comment'
    }
}, {
    timestamps: true
});

var BlogEntry = new Schema({
    title: String,
    thumbnailUrl: String,
    content: String,
    comments: [Comment]
}, {
    timestamps: true
});

var Blog = new Schema({
    createdBy: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    name: {
        type: String,
        required: true
    },
    headerImageUrl: String,
    description: String,
    blogEntries: [BlogEntry]
}, {
    timestamps: true
});

module.exports = mongoose.model('Blog', Blog);

Sooo ......我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

当您使用单独的文件工作时,您需要保证&#39;评论&#39;架构是在BlogEntry&#39;之前加载的。架构。

您只需在BlogEntry.js顶部添加require('./comment.js')即可。例如:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Comment = require('./comment.js');

var BlogEntry = new Schema({
    title: String,
    thumbnailUrl: String,
    content: String,
    comments: [Comment]
}, {
    timestamps: true
});