嵌入式文档没有数组

嵌入式文档没有数组

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

问题描述

我了解如何在Mongoose中,如果他们似乎很简单存储为数组,用例相当明显:

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

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

  var UserSchema = new Mongoose.Schema({...}); 
var BlogPostSchema = new Mongoose.Schema({
author:??? //'UserSchema'和UserSchema不在这里工作
});

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

解决方案

您不能以这种方式嵌入模式,推理这些小孩文档将与完整文档混淆,请参阅,其中说明:



我们以前没有添加这个支持的原因是b / c,这让我们想知道如果所有的预挂钩都将以相同的方式执行伪小孩文档,以及这意味着我们可以在该孩子上调用save()。


这里的答案是不分享模式,而只是定义。

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

这将导致嵌套的用户对象,而不会实际嵌套模式。


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.
});

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:

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.

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

07-30 18:37