如何解决将 2 列中的 json 数据与架构中的数据进行比较,并将最新数据覆盖到 mongoos 中的主要数据
我正在尝试从 json 数据构建一个页面, “page_content”列将包含 json,而“override_content”列将包含一个或多个带有键的 json 部分。 “override_content”将始终具有最新更新,如果列为空则没有覆盖数据。 预期结果是使用内部json“id”比较“page_content”和“override_content”列中的数据,并将“page_content”中的内容替换为“override_content”列
下面是例子
“page_content”中的数据如下所示, 组件有 3 个孩子,每个孩子都有唯一的“id”
{
"components":[
{
"id":"uibuilder:fa10894e44b3460c93912198a99e3629","component":{
"name":"Hero","properties":{
"imageUrl":"https://images.unsplash.com/photo-1532298229144-0ec0c57515c7?ixid=MnwxMjA3fdb8MHxwaG90by1wYWdlfHx8fGVufdb8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2000&q=80","caption1":"New Collection","caption2":"About this collection","buttonText":"Click Me!"
}
},"componentStyle":{
"large":{
"display":"flex","flexDirection":"column","position":"relative","flexShrink":"0","BoxSizing":"border-Box","marginTop":"20px","minHeight":"20px","minWidth":"20px","overflow":"hidden"
}
}
},{
"id":"uibuilder:8818c12fe5c94b27b7f7033fec7910b6","component":{
"name":"Text","properties":{
"text":"<p>This iss text</p>"
}
},{
"id":"uibuilder:8818c12fe5c94b25c94b23fec033fec7","component":{
"name":"Text New","properties":{
"text":"<b>Component heading</b>"
}
},"marginTop":"10px","minHeight":"10px","minWidth":"10px","overflow":"hidden"
}
}
}
]
}
“override_content”列包含第一个和第三个孩子的最新数据,如下所示,
{
"components":[
{
"id":"uibuilder:fa10894e44b3460c93912198a99e3629","caption1":"Faucet Collection","caption2":"","marginTop":"50px","minHeight":"50px","minWidth":"50px","overflow":"hidden"
}
}
}
]
}
预期结果: 按子“id”比较两个列数据。 用“覆盖内容”替换“page_content”中的第一个和第三个孩子 保留“page_content”中的第二个孩子
{
"components":[
{
"id":"uibuilder:fa10894e44b3460c93912198a99e3629","overflow":"hidden"
}
}
}
]
}
我在 Expressjs 中的 API 如下所示,Pages 是集合 我正在尝试使用猫鼬聚合
router.get('/pages/findit/:_id',(req: Request,res: Response) => {
const id = req.params._id;
if (id && id.length > 0) {
const pid = mongoose.Types.ObjectId(id);
Pages.aggregate([
{
$match: { _id: pid }
}
]).exec((err,data) => {
if (err) { res.status(HttpStatusEnum.badserver).json(err); return; };
let result: IResponse = {
data: data
};
res.status(HttpStatusEnum.success).json(result);
});
}
});
谢谢
解决方法
通过Mongoose聚合无法找到方法,而是使用外部方法来比较和合并json数组,一旦我们从集合中获得结果将数据传递到下面的脚本中进行比较和合并, (在我的情况下,一次记录需要合并操作)
const sourceJson: { components: [{ id: 'a' },{ id: 'b',test: 'a' }] };
const customJson: { components: [{ id: 'b',test: 'b' },{ id: 'c' }] };
const result = sourceJson.components.map(sj => ({
...sj,...customJson.components.find(cj => sj.id === cj.id)
}))
return result;
输出:
{"components":[{"id":"a"},{"id":"b","test":"b"},{"id":"c"}]}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。