Я довольно новичок в стеке MEAN, поэтому, возможно, я делаю что-то невероятно глупое.Ошибки проверки вложенной схемы Mongoose
У меня есть несколько определенных схем (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.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;
Когда схема комментариев находится в сепараторе е файл, и я отправляю следующий запрос, я получаю сообщение об ошибке проверки:
{
"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 файла и переместить комментарий схему в 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 ... что я делаю неправильно здесь?
Сделал указанное вами изменение, развернуто на сервере и по-прежнему получает ту же ошибку. Интересно, что вложенная ссылка на пользователя работает нормально, даже если это находится в другом файле и явно не требуется в этом файле схемы. –
Если вы используете пользователя в другой точке вашего кода (вероятно, в функции verifyOrdinaryUser). Затем предыдущие «требуют» добавили его в кэш мангуста. Сохраните '' 'require ('./ comment.js')' '' и попробуйте изменить '' 'комментарии: [Комментарий]' '' to '' 'comments: [{ type: Schema.Types. ObjectId, ref: 'Comment' }] '' ' –
Я согласен с этим @Rafael, это первое использование comment.js, поэтому оно должно быть в инструкции require. Я пробовал использовать оба комментария: [Комментарий] 'и' comments: [{type: Schema.Types.ObjectId, ref: 'Comment'}] ', но получить одинаковые ошибки в обоих случаях. –