绞尽脑汁用 Mongoose 创建一个嵌入式文档。提交表单时出现以下错误:
500 CastError: Cast to undefined_method 值“comment going here”失败
代码:
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('/');
});
};
数据库.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")