架起我的大脑用Mongoose创建一个嵌入式文档。提交表单时出现以下错误:
500 CastError:施放到undefined_method失败,因为值“评论在这里”
代码:
index.js
var db = require( 'mongoose' );
var Todo = db.model( 'Todo' );
exports.create = function(req, res, next){
new Todo({
title : req.body.title,
content : req.body.content,
comments : req.body.comments,
}).save(function(err, todo, count){
if( err ) return next( err );
res.redirect('/');
});
};
db.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// recursive embedded-document schema
var commentSchema = new Schema();
commentSchema.add({
content : String
, comments : [Comment]
});
var Comment = mongoose.model('Comment', commentSchema);
var todoSchema = new Schema({
title : { type: String, required: true }
, content : String
, comments : [Comment]
});
var Todo = mongoose.model('Todo', todoSchema);
玉形
form(action="/create", method="post", accept-charset="utf-8")
input.inputs(type="text", name="title")
input.inputs(type="text", name="content")
input.inputs(type="text", name="comments")
input(type="submit", value="save")
答案 0 :(得分:5)
要使嵌套/嵌入文档起作用,必须使用.push()方法。
var Comment = new Schema({
content : String
, comments : [Comment]
});
var Todo = new Schema({
user_id : String
, title : { type: String, required: true }
, content : String
, comments : [Comment]
, updated_at : Date
});
mongoose.model('Todo', Todo);
mongoose.model('Comment', Comment);
exports.create = function(req, res, next){
var todo = new Todo();
todo.user_id = req.cookies.user_id;
todo.title = req.body.title;
todo.content = req.body.content;
todo.updated_at = Date.now();
todo.comments.push({ content : req.body.comments });
todo.save(function(err, todo, count){
if( err ) return next( err );
res.redirect('/');
});
};
答案 1 :(得分:0)
mongoose模型永远不会涉及模式。只有基本数据类型和mongoose模式。不确定是否有带递归评论模式的问题,但尝试这样的事情。
var commentSchema = new Schema();
commentSchema.add({
, content : String
, comments : [commentSchema]
});
var todoSchema = new Schema({
, title : { type: String, required: true }
, content : String
, comments : [commentSchema]
});
var Todo = mongoose.model('Todo', todoSchema);
var Comment = mongoose.model('Comment', commentSchema);