【问题标题】:Mongoose populate to a static arrayMongoose 填充到静态数组
【发布时间】:2021-04-04 12:11:35
【问题描述】:

我有一个架构和一个数组

这是我的架构

const schema = new Schema({
    distributor_id: {
        type: String
    },
    user_id: {
        type: String
    },
    customer_id: {
        type: String
    },
    problem: {
        type: Number,
        required: true
    },
    note: {
        type: String,
        required: true
    },
    created_at: {
        type: Date,
        required: true
    },
    created_by: {
        type: String,
        required: true
    },
    updated_at: {
        type: Date
    },
    updated_by: {
        type: String
    },
}

这是我的数组数据

let problem_data = [{
            value: 1,
            label: 'error bill',
        },{
            value: 2,
            label: 'error system',
        },{
            value: 3,
            label: 'error connection',
        }]

我的结果数据是这样的:

"_id": "5fe86f3d6ff4936d7344d245",
"user_id": "5fa4f1c85d68ba373e2fb0b9",
"customer_id": "5f44e031cb22f81906cc1c6a",
"problem": 1,

我想要的结果是这样的

"_id": "5fe86f3d6ff4936d7344d245",
"user_id": "5fa4f1c85d68ba373e2fb0b9",
"customer_id": "5f44e031cb22f81906cc1c6a",
"problem": {
     value: 1,
     label: 'error bill'
},

我的问题是是否可以基于数组填充猫鼬模式? 如果可能的话你们如何解决这个问题?或者我可以问一些关键字吗?

【问题讨论】:

    标签: node.js arrays mongoose populate mongoose-populate


    【解决方案1】:

    这是我解决这个问题的棘手方法 我这样做是因为我在客户端的前端会询问我上面提供的格式的数据

    首先我将架构类型更改为:

    problem: {
         type: Object,
         required: true
    },
    

    然后在我的插入 API 中执行此操作

    let {problem} = req.body
    
     if(problem == `1`){
         problem  = { "value": 1, "label": "error bill" }
     }
    
     if(problem == `2`){
          problem  = { "value": 2, "label": "error system" }
     }
    
     if(problem == `3`){
           problem  = { "value": 3, "label": "error connection" }
     }
    

    【讨论】:

      【解决方案2】:

      我认为你应该在你的客户端做,

      • 这是您的数组数据:
      let problem_data = [
        { value: 1, label: 'error bill' },
        { value: 2, label: 'error system' },
        { value: 3, label: 'error connection' }
      ];
      
      • pData中创建一个数组数据对象:
      let pData = {};
      for (let p in problem_data) {
          pData[problem_data[p].value] = problem_data[p].label;
      }
      
      • 根据您的要求查询:
      let result = await SchemaModel.find();
      
      • 只需从查询中迭代result 的循环并从pData 对象中替换问题
      result.forEach(function(doc) {
          doc.problem = {
            label: pData[doc.problem],
            value: doc.problem
          };
      });
      

      【讨论】:

      • 我想我同意你的看法,谢谢你回答我的问题,问题是我的客户端要求像我上面提供的格式一样的数据我发现了一个棘手的方法,我将在 cmets 中描述它列
      猜你喜欢
      • 2015-01-22
      • 2019-01-31
      • 2014-12-05
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 2015-03-26
      相关资源
      最近更新 更多