如何在mongoose模式中引用嵌套的ObjectId

nnsrf1az  于 2022-12-27  发布在  Go
关注(0)|答案(1)|浏览(153)

这是我的类别架构,我在其中嵌套了nestedCategorySchema,并且希望在其他集合中引用this的此ObjectId
'

const mongoose = require("mongoose");

const { Schema } = mongoose;

const nestedCategorySchema = new Schema({
  name: {
    type: Schema.Types.ObjectId,
  },
});

const categorySchema = new Schema(
  {
    clientname: {
      type: Schema.Types.String,
    },
    categoryOne: {
      type: [nestedCategorySchema],
      default: [],
    },
    categoryTwo: {
      type: [nestedCategorySchema],
      default: [],
    },
  },
  {
    timestamps: true,
  }
);

exports.default = mongoose.model("category", categorySchema);

mongoose.model("category").collection.createIndex({
  clientname: 1,
});

'
在另一个集合中,我希望引用嵌套的categoryOneObjectId
'

const mongoose = require("mongoose");

const { Schema } = mongoose;

const prodSchema = new Schema(
  {
    categories: [
      {
        _id: false,
        clientname: {
          type: String,
        },
**        categoryLevelOne: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "category.categoryOne",
        },**
      },
    ],
  },
  {
    timestamps: true,
  }
);

'
在prodSchema中,我希望引用嵌套的categoryOne

ig9co6j1

ig9co6j11#

尝试将nestedCategorySchema声明为模型:

mongoose.model("nestedCategory", nestedCategorySchema);

并将categorySchema中的categoryOne属性更改为ObjectId引用:

categoryOne: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'nestedCategory',
    default: []
}];

最后,根据您的配置,您可能应该将prodSchema中的categories属性更改为ref本身:

const prodSchema = new Schema(
  {
    categories: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'category'
      },
    ],
  },
  {
    timestamps: true,
  }
);

mongoose中,只能创建对ObjectId的引用。

相关问题