没有数组的嵌入文档? [英] Embedded document without Array?

查看:20
本文介绍了没有数组的嵌入文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解如何在 Mongoose 中嵌入文档,如果存储为数组,其用例相当明显:

I understand how to embed documents in Mongoose, and they seem fairly straightforward if storing as arrays, for which the use case is fairly obvious:

var CommentSchema = new Mongoose.Schema({...});
var BlogPostSchema = new Mongoose.Schema({
    comments : [CommentSchema],
});

但是,在向前和向后查看文档后我没有看到如何做的是如何存储不需要或不想在数组中的单个子文档.

But, what I don't see how to do after looking over the documentation forward and backward, is how to store a single sub-document that doesn't need or want to be in an Array.

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

有什么办法可以使这个工作?我不想只存储 ObjectId,而是存储用户记录的完整副本,但不需要或不需要数组.

Is there any way to make this work? I don't want to just store the ObjectId, but rather, store a complete copy of the User record, but don't need or want an array.

推荐答案

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

You cannot embed schemas in this way, with the reasoning that those child docs would be confused with full documents, see this bug thread, where it is stated:

我们过去没有添加这个支持的原因是 b/c 这让我们想知道是否所有的 pre-hooks 都会以相同的方式执行伪子文档,并且这意味着我们可以调用 save() 在那个孩子身上.

the reason we haven't added this support in the past is b/c this leaves us wondering if all pre-hooks will be executed the same way for the pseudo-child document as well as it implies that we can call save() on that child.

这里的答案不是共享架构,而是共享定义.

The answer here is to share not the schema, but just the definition.

var userdef = { name: String };
var UserSchema = new Schema(userdef);
var BlogPostSchema = new Schema({author: userdef});

这将导致嵌套用户对象,而实际上并未嵌套架构.

This would result in a nested user object, without actually nesting the Schema.

这篇关于没有数组的嵌入文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆