【发布时间】:2012-10-06 02:07:21
【问题描述】:
我找不到我做错了什么... 我正在尝试在 mongoose 模型中定义子文档,但是当我将 Schema 定义拆分到另一个文件中时,不尊重子模型。
首先,定义一个评论模式:
var CommentSchema = new Schema({
"text": { type: String },
"created_on": { type: Date, default: Date.now }
});
mongoose.model('Comment', CommentSchema);
接下来,通过从 mongoose.model() 加载创建另一个模式(就像我们从另一个文件加载它一样
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);
还有一些测试
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,它会出错。
我尝试使用“人口”版本,但这不是我想要的。我不想使用其他集合。
有谁知道怎么回事?谢谢!
猫鼬 v3.3.1
nodejs v0.8.12
【问题讨论】:
标签: javascript node.js mongoose