2013-07-02 51 views
1

將我的大腦架起來使用Mongoose創建嵌入式文檔。我收到以下錯誤,當我提交表單:使用Mongoose和Express創建嵌入式文檔

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") 

回答

4

要使嵌套/嵌入式文檔起作用,您必須使用.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('/'); 
    }); 
}; 
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); 
+0

我只是想你的代碼,並刪除第一個逗號的模式上的。這裏是我收到的錯誤: Express 500 TypeError:不能使用'in'運算符來搜索'_id'在評論去這裏 – omer3210

+0

我認爲問題在於index.js上的Express代碼 – omer3210

+0

啊,是的,所以你可以只是將一些javascript對象粘貼到註釋中,您需要先將它們轉換爲mongoose註釋模型實例,然後將Todo與嵌入的註釋一起保存。 –