Is there a way to autopopulate a mongoose field with a string?

232 views Asked by At

I have a Item schema with an array of categories where I store some ids :

const schema = new Schema<Item>(
...
categories:[
 {
   type: Schema.Types.ObjectId,
   ref: 'Category',
   autopopulate: { select:'name'}
 }
]
...
)

Category:

const schema = new Schema<Category>({
  slug: {
    type: String,
    required: true,
    unique: true,
    index: true,
  },
  name:{
    type: String,
    required:true,
  }
});

and I am using the mongoose-autopopulate package at the moment.

Is there a way to replace the ids in the Item schema with the appropriate name when queried (with or without mongoose-autopopulate) ?

1

There are 1 answers

8
Lars Vonk On

I think what you want is to use .populate with an object passed in. I found this in the mongoose documentation

// The 2nd `populate()` call below overwrites the first because they
// both populate 'fans'.
Story.
  find().
  populate({ path: 'fans', select: 'name' }).
  populate({ path: 'fans', select: 'email' });
// The above is equivalent to:
Story.find().populate({ path: 'fans', select: 'email' });

https://mongoosejs.com/docs/populate.html

In your case I think you need to use .populate({ path: 'categories', select: 'name' });