使用Mongoose和Express创建嵌入式文档

ome*_*210 1 mongoose express pug

绞尽脑汁用Mongoose创建嵌入式文档。提交表单时出现以下错误:

500 CastError:转换为undefined_method失败,原因是值“ comment go 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('/');
  });
};
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

翡翠形式

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")
Run Code Online (Sandbox Code Playgroud)

ome*_*210 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);
Run Code Online (Sandbox Code Playgroud)
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('/');
  });
};
Run Code Online (Sandbox Code Playgroud)