【问题标题】:Mongoose Nested Schema Validation ErrorsMongoose 嵌套模式验证错误
【发布时间】:2016-09-15 09:54:58
【问题描述】:

我对 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...我在这里做错了什么?

【问题讨论】:

    标签: mongoose-schema


    【解决方案1】:

    当您使用单独的文件时,您需要保证在“BlogEntry”架构之前加载“评论”架构。

    您只需在 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
    });
    

    【讨论】:

    • 进行了您提到的更改,部署到服务器,但仍然出现相同的错误。有趣的是,对 User 的嵌套引用可以正常工作,即使它位于不同的文件中,并且在此架构文件中没有明确要求。
    • 如果您在代码的另一点使用 User(可能在 verifyOrdinaryUser 函数中)。然后之前的“要求”将其添加到猫鼬缓存中。保留require('./comment.js') 并尝试将comments: [Comment] 更改为comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
    • 我同意@Rafael,这是第一次使用comment.js,所以它应该在require 语句中。我尝试过同时使用comments: [Comment] 和comments: [{ type: Schema.Types.ObjectId, ref: 'Comment'}],但在这两种情况下都会出现相同的错误。
    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 2012-10-09
    • 2022-01-15
    • 2014-03-02
    • 1970-01-01
    • 2013-11-13
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多