【问题标题】:How can i populate a model data while fetching it?Mongodb如何在获取模型数据时填充模型数据?Mongodb
【发布时间】:2021-06-30 12:23:42
【问题描述】:

我有两个模型的架构,一个是Category,另一个是subCategory。我们需要Category 来创建子类别模型,但Category 模型不必有subCategories。 这是我的subCategory 模型:

const Mongoose = require('mongoose');
const { Schema } = Mongoose;
// Brand Schema
const SubCategorySchema = new Schema({
  name: {
    type: String,
    required:true
  },
  id: {
    type:  Schema.Types.String,
    unique:true,
    required:true
  },
  category: {
    type: Schema.Types.ObjectId,
    ref: 'Category',
    required:true
  },
  updated: Date,
  created: {
    type: Date,
    default: Date.now
  }
});

module.exports = Mongoose.model('SubCategory', SubCategorySchema);

这是我的Category 模型:

const Mongoose = require('mongoose');
const { Schema } = Mongoose;

// Category Schema
const CategorySchema = new Schema({
  name: {
    type: String,
    trim: true,
  },
  id: {
    type: String,
    required:true,
    unique: true
  },
  image: {
    type:String,
    default:'http://res.cloudinary.com/wisecart/image/upload/v1616718691/kuy26lytx5k0lkvfkgrt.svg',
    required:true
  },
  description: {
    type: String,
    trim: true
  },
  updated: Date,
  created: {
    type: Date,
    default: Date.now
  },

});

module.exports = Mongoose.model('Category', CategorySchema);

我正在使用 请求类别时如何填充子类别? 例如,我想得到一个响应

{

  "image": "http://res.cloudinary.com/wisecart/image/upload/v1616718691/kuy26lytx5k0lkvfkgrt.svg",
  "_id": "606605934b213d2887e3a840",
  "name": "Samsung",
  "description": "sama",
  "id": "asa",
  "subCategory": [{Subcategory with an Id of _id},{Subcategory with an Id of _id}],
  "created": "2021-04-01T17:40:35.505Z",
  "__v": 0
}

【问题讨论】:

  • 是否要填充 SubCategorySchema 的类别字段?
  • 是否要填充 SubCategorySchema 的类别字段?

标签: javascript node.js mongodb typescript mongoose


【解决方案1】:

你必须使用aggregation查询

演示 - https://mongoplayground.net/p/ItN9R9AlE4A

使用$lookup

对同一数据库中的未分片集合执行左外连接,以过滤来自“已连接”集合的文档以进行处理。对于每个输入文档,$lookup 阶段添加一个新的数组字段,其元素是“加入”集合中的匹配文档。 $lookup 阶段将这些重新调整的文档传递到下一个阶段。

https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

db.category.aggregate([
  {
    "$lookup": {
      "from": "subCategory", // collection name
      "localField": "_id",
      "foreignField": "category",
      "as": "subCategory"
    }
  }
])

【讨论】:

    猜你喜欢
    • 2013-12-06
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2014-12-13
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多