gpt4 book ai didi

mongodb - 没有数组的嵌入文档?

转载 作者:IT老高 更新时间:2023-10-28 13:05:37 24 4
gpt4 key购买 nike

我了解如何 embed documents在 Mongoose 中,如果存储为数组,它们看起来相当简单,用例相当明显:

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

但是,在向前和向后查看文档后,我不知道如何存储一个不需要或不想放在数组中的单个子文档。

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

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

最佳答案

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

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.

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

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

这将产生一个嵌套的用户对象,而实际上并没有嵌套架构。

关于mongodb - 没有数组的嵌入文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com