有没有一种方法可以自动填充mongoose字段为字符串?

huangapple go评论129阅读模式
英文:

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

问题

以下是您提供的代码的翻译部分:

我有一个Item模式,其中有一个存储一些id的类别数组:

  1. const schema = new Schema<Item>(
  2. ...
  3. categories: [
  4. {
  5. type: Schema.Types.ObjectId,
  6. ref: 'Category',
  7. autopopulate: { select: 'name' }
  8. }
  9. ]
  10. ...
  11. )

类别:

  1. const schema = new Schema<Category>({
  2. slug: {
  3. type: String,
  4. required: true,
  5. unique: true,
  6. index: true,
  7. },
  8. name:{
  9. type: String,
  10. required:true,
  11. }
  12. });

我目前正在使用mongoose-autopopulate包。

是否有一种方法可以在查询Item模式时用适当的name替换ids(无论是否使用mongoose-autopopulate)?

英文:

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

  1. const schema = new Schema&lt;Item&gt;(
  2. ...
  3. categories:[
  4. {
  5. type: Schema.Types.ObjectId,
  6. ref: &#39;Category&#39;,
  7. autopopulate: { select:&#39;name&#39;}
  8. }
  9. ]
  10. ...
  11. )

Category:

  1. const schema = new Schema&lt;Category&gt;({
  2. slug: {
  3. type: String,
  4. required: true,
  5. unique: true,
  6. index: true,
  7. },
  8. name:{
  9. type: String,
  10. required:true,
  11. }
  12. });

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

得分: 1

我认为你想要使用.populate并传入一个对象。我在mongoose文档中找到了这个例子:

  1. // 下面的第二个`populate()`调用会覆盖第一个,因为它们都在'fans'字段上执行populate。
  2. Story.
  3. find().
  4. populate({ path: 'fans', select: 'name' }).
  5. populate({ path: 'fans', select: 'email' });
  6. // 上述代码等同于:
  7. Story.find().populate({ path: 'fans', select: 'email' });

在你的情况下,我认为你需要使用.populate({ path: 'categories', select: 'name' });

英文:

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

  1. // The 2nd `populate()` call below overwrites the first because they
  2. // both populate &#39;fans&#39;.
  3. Story.
  4. find().
  5. populate({ path: &#39;fans&#39;, select: &#39;name&#39; }).
  6. populate({ path: &#39;fans&#39;, select: &#39;email&#39; });
  7. // The above is equivalent to:
  8. Story.find().populate({ path: &#39;fans&#39;, select: &#39;email&#39; });

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

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

huangapple
  • 本文由 发表于 2023年3月7日 17:25:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定