为什么mongoose.model('Model')。模式出错了?

我无法find我在做什么错…我试图在mongoose模型中定义子文档,但是当我将模式定义分割到另一个文件时,儿童模型不受尊重。

首先,定义一个评论模式:

var CommentSchema = new Schema({ "text": { type: String }, "created_on": { type: Date, default: Date.now } }); mongoose.model('Comment', CommentSchema); 

接下来,通过从mongoose.model()加载来创build另一个模式(就像我们将从另一个文件加载它一样

 var CommentSchema2 = mongoose.model('Comment').Schema; 

现在定义父模式:

 var PostSchema = new Schema({ "title": { type: String }, "content": { type: String }, "comments": [ CommentSchema ], "comments2": [ CommentSchema2 ] }); var Post = mongoose.model('Post', PostSchema); 

还有一些testing

 var post = new Post({ title: "Hey !", content: "nothing else matter" }); console.log(post.comments); // [] console.log(post.comments2); // [ ] // <-- space difference post.comments.unshift({ text: 'JOHN' }); post.comments2.unshift({ text: 'MICHAEL' }); console.log(post.comments); // [{ text: 'JOHN', _id: 507cc0511ef63d7f0c000003, created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) }] console.log(post.comments2); // [ [object Object] ] post.save(function(err, post){ post.comments.unshift({ text: 'DOE' }); post.comments2.unshift({ text: 'JONES' }); console.log(post.comments[0]); // { text: 'DOE', _id: 507cbecd71637fb30a000003, created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) } // :-) console.log(post.comments2[0]); // { text: 'JONES' } // :'-( post.save(function (err, p) { if (err) return handleError(err) console.log(p); /* { __v: 1, title: 'Hey !', content: 'nothing else matter', _id: 507cc151326266ea0d000002, comments2: [ { text: 'JONES' }, { text: 'MICHAEL' } ], comments: [ { text: 'DOE', _id: 507cc151326266ea0d000004, created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) }, { text: 'JOHN', _id: 507cc151326266ea0d000003, created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) } ] } */ p.remove(); }); }); 

正如你所看到的,使用CommentSchema,正确设置了id和默认属性。 但是与CommentSchema2,加载一个,这是错误的。

我尝试过使用“人口”版本,但这不是我正在寻找的。 我不想用另一个集合。

你们有谁知道什么是错的? 谢谢 !

mongoosev3.3.1

nodejs v0.8.12

充分的要点: https : //gist.github.com/de43219d01f0266d1adf

模型的模式对象可以作为Model.schema访问,而不是Model.Schema

所以把你的要点20行改为:

 var CommentSchema2 = mongoose.model('Comment').schema;