猫鼬填充到静态数组

问题描述

我有一个架构和一个数组

这是我的架构

const schema = new Schema({
    distributor_id: {
        type: String
    },user_id: {
        type: String
    },customer_id: {
        type: String
    },problem: {
        type: Number,required: true
    },note: {
        type: String,created_at: {
        type: Date,created_by: {
        type: String,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","problem": {
     value: 1,label: 'error bill'
},

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

解决方法

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

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

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" }
 }
,

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

  • 这是您的数组数据:
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
    };
});

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...