如何防止猫鼬创建收藏集?

时间:2019-11-28 08:45:15

标签: mongoose

我在应用程序中定义了两个模式:模式A是“主”文档,模式B嵌入了从模式A生成的文档中。现在,模式B设置了_id属性,并且一切正常。但是,当我访问任何文档时,都会为模式B类型的对象创建一个新的空集合,因为mongoose认为模式B对象具有自己的集合(而没有)。 有没有办法告诉猫鼬不要创建这个集合?我尝试在模式B定义上设置{_id: false}{strict: false}选项,但是没有用

这是架构B的定义

const SchemaBDefinition = new Schema(
  {
    position: Number,
    title: String,
    ...
  },
  { _id: false }
);

const SchemaBModel = db.model("SchemaB", SchemaBDefinition );

exports.model = SchemaBModel;

这就是我在架构A中使用它的方式

const { model: SchemaBModel } = require("./schemaB");

const SchemaADefinition = new Schema(
  {
    name: String,
    refs: [SchemaBModel],
    ...
  }
);

1 个答案:

答案 0 :(得分:2)

如果您不想为SchemaB生成集合,则不应在const SchemaBModel = db.model("SchemaB", SchemaBDefinition );

处为schemaB创建模型。

我认为您要尝试将SchemaB嵌入SchemaA。

如果是这样,您只需这样做:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const SchemaBDefinition = new Schema(
  {
    position: Number,
    title: String
  },
  { _id: false }
);

const SchemaADefinition = new Schema({
  name: String,
  refs: [SchemaBDefinition]
});

const SchemaAModel = mongoose.model("ModelA", SchemaADefinition);

exports.model = SchemaAModel;