在Loopback 3中,如何在MongoDB的嵌套文档中转换ID属性并将其作为ObjectId插入

时间:2019-02-22 14:14:49

标签: mongodb loopback

我最近开始探索POC的Loopback 3。我正在使用MongoDB连接器,并且有一个用例,其中在MongoDB中有一个带有嵌套记录的文档,可以解决该问题。我尝试按照文档理解的所有可能方式将自动Id转换为MongoId并插入嵌套数组中,但仍然仅作为字符串插入。我的解决方法用例在这里:

Profile.json

{
"name": "profile",
"base": "PersistedModel",
"idInjection": true,
"options": {
    "validateUpsert": true
},
"properties": {
    "name": {
        "type": "string",
        "required": true
    },
    "mobile": {
        "type": "string",
        "required": true
    },
    "isActive": {
        "type": "boolean",
        "required": true,
        "default": true
    },
    "isBusy": {
        "type": "boolean",
        "required": true,
        "default": true
    }
},
"validations": [],
"relations": {
    "customer": {
        "type": "belongsTo",
        "model": "customer",
        "foreignKey": "userId",
        "options": {
            "nestRemoting": true
        }
    },
    "address": {
        "type": "embedsOne",
        "model": "address",
        "foreignKey": "",
        "property": "address",
        "options": {
            "nestRemoting": true
        }
    },
    "plants": {
        "type": "embedsMany",
        "model": "plants",
        "property": "plants",
        "foreignKey": "",
        "options": {
            "nestRemoting": true,
            "forceId": true,
            "persist": true
        }
    }
},
"acls": [],
"methods": {}
}

临时模型:Plant.json

{
"name": "plants",
"base": "Model",
"options": {
    "validateUpsert": true,
    "strictObjectIDCoercion": true
},
"properties": {
    "data": {
        "type": "string"
    },
    "city": {
        "type": "string"
    },
    "state": {
        "type": "string"
    },
    "pin": {
        "type": "number"
    }
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

在我尝试过的profile.json中

  "options": {
       "nestRemoting": true,
       "forceId": true,
       "persist": true
   }

在我尝试过的plants.json中

"idInjection": true,

"id": {
  "type": "string",
  "id": true,
  "defaultFn": "uuid"
}

generated: true

任何人都可以做类似的解决方法,请提供您的建议。 谢谢

JS文件解决方法

module.exports = function(Plants) {
Plants.observe('before save', function (ctx, next) {
    let id = ObjectId(ctx.instance.id);
    ctx.instance.id = id;
    next();
});
};

0 个答案:

没有答案