1

绞尽脑汁用 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")
4

2 回答 2

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('/');
  });
};
于 2013-07-04T03:42:08.350 回答
0

猫鼬模型从不参与模式。只有基本数据类型和猫鼬模式。不确定是否存在带有递归注释模式的陷阱,但请尝试类似的方法。

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);
于 2013-07-02T06:10:57.183 回答