嵌入式文件没有数组?

bme*_*ton 20 mongoose mongodb express

我理解如何在Mongoose中嵌入文档,如果存储为数组,它们看起来相当简单,用例非常明显:

var CommentSchema = new Mongoose.Schema({...});
var BlogPostSchema = new Mongoose.Schema({
    comments : [CommentSchema],
});
Run Code Online (Sandbox Code Playgroud)

但是,在向前和向后查看文档之后我看不到该怎么做,是如何存储不需要或想要在Array中的单个子文档.

var UserSchema = new Mongoose.Schema({...});
var BlogPostSchema = new Mongoose.Schema({
    author: ??? // 'UserSchema' and UserSchema do not work here. 
});
Run Code Online (Sandbox Code Playgroud)

有没有办法让这项工作?我不想只存储ObjectId,而是存储用户记录的完整副本,但不需要或不需要数组.

num*_*407 18

您不能以这种方式嵌入模式,因为这些子文档会与完整文档混淆,请参阅此错误线程,其中说明:

我们之前没有添加这种支持的原因是b/c这让我们想知道是否所有预挂钩都将以相同的方式执行伪子文档,这意味着我们可以调用save()那个孩子.

这里的答案是分享模式,而不仅仅是定义.

var userdef = { name: String };
var UserSchema = new Schema(userdef);
var BlogPostSchema = new Schema({author: userdef});
Run Code Online (Sandbox Code Playgroud)

这将导致嵌套的用户对象,而不实际嵌套Schema.