1

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) ?

Riadh Adrani
  • 486
  • 2
  • 5
  • 16

1 Answers1

1

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

Lars Vonk
  • 623
  • 5
  • 13
  • Isn't it the same as I have right now ? using the `autopopulate: { select:'name'}` key in the schema ? – Riadh Adrani Mar 07 '23 at 10:13
  • Oh you are right.... did not read your question well, I think to you can use `.virtual` for this, I have personally not used this before but when looking through the documentation this seems to be able to populate fields based on other values than `ids` – Lars Vonk Mar 07 '23 at 10:18
  • To get a clear understanding of what you want, you want to save an `Item` with the `categories` property not having the `_id`s to refer to the `Category` but the `name` to refer to the category right? – Lars Vonk Mar 07 '23 at 10:19
  • Yes, I want to retrieve an `Item` but the `categories` are replaced by `name`s instead of `_id`s. – Riadh Adrani Mar 07 '23 at 10:22
  • So you want it to be saved in the database as just `_id`s like it is supossed to but a query where you get the `categories` as an array of strings with the `name`? – Lars Vonk Mar 07 '23 at 10:28
  • I think autoPopulate does not support what you are trying to do I think my answer is still valid if you query it like this it should returns it like my question is above this. – Lars Vonk Mar 07 '23 at 10:30
  • I made my research too, I didn't find any solution for my question and I don't think there is one at the moment, maybe in the future it will be possible. but hey thank you for the help. – Riadh Adrani Mar 07 '23 at 10:32
  • I think it is possible with `.populate` but not with `autopopulate`, also the way it is used is passing it to a field like you are doing but giving it a `Boolean` value. – Lars Vonk Mar 07 '23 at 10:35