Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.95k stars 3.84k forks source link

Reuse subschema contains refPath #12773

Closed conduongtong closed 1 year ago

conduongtong commented 1 year ago

Prerequisites

Mongoose version

6.7.4

Node.js version

18.12.1

MongoDB version

6.0.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

No response

Issue

I have schemas like this:

const childSchema = new Schema({
    title: String,
    type: { type: String, enum: ['Test'] },
    test: { type: Schema.Types.ObjectId, refPath: 'child.type' },
  });
  const parentSchema = new Schema({ title: String, child: childSchema });

It works. But I want to use childSchema on another schema like this:

  const subAnotherSchema = new Schema({ title: String, child: childSchema });
  const anotherSchema = new Schema({ title: String, subAnother: subAnotherSchema });

Because refPath nested another schema so refPath now wrong. How can I reuse childSchema?

conduongtong commented 1 year ago

I solved by using replace refPath: 'child.type' to ref: function(child) { return child.type; }

vkarpov15 commented 1 year ago

Use ref function instead of refPath. As you saw, refPath is relative to the top-level document, which makes it tricky to reuse schemas. If you use ref: function() { return this.type; }, that's relative to the subdocument, which is better for schema reuse.