MongoDB 如何存储多级嵌套数据及操作增删改查❓

我有一个关于权限列表管理的需求,数据库固定使用 MongoDB,前端接收的数据格式如下:

interface Access {
id: string;
parentId?: string;
name: string;
code: string;
children?: Array<Access>
}[];

这种数据结构我应该以什么方式来存储到MongoDB中最好❓以及如何操作数据呢❓

大致需求如下:

1. 查询权限:返回所有的数据,格式为 Array<Access>

2. 添加权限:前端传过来的参数是 {parentId, name, code},然后我找到parentId 的记录,在 children 里面添加数据即可。

3. 编辑权限:前端传过来的参数是 {id, name, code},然后我找到id的记录,修改name和code。

4. 删除权限:前端传过来的参数是 {id},然后我找到id的记录,删除该条以及该条嵌套的children记录。

辛苦各位大佬帮忙解决,感激不尽。
最新回答
梦已隔江南

2024-07-27 00:45:39

针对这个需求,可以考虑使用 MongoDB 的嵌套文档来存储权限列表。可以将权限列表存储为一个文档,其中每个权限都是一个嵌套的子文档。下面是一个示例文档:

{

"_id": ObjectId("123456789012345678901234"),

"name": "权限列表",

"access": [

{

"id": "1",

"name": "权限1",

"code": "code1",

"children": [

{

"id": "11",

"name": "权限1-1",

"code": "code1-1"

},

{

"id": "12",

"name": "权限1-2",

"code": "code1-2",

"children": [

{

"id": "121",

"name": "权限1-2-1",

"code": "code1-2-1"

}

]

}

]

},

{

"id": "2",

"name": "权限2",

"code": "code2",

"children": [

{

"id": "21",

"name": "权限2-1",

"code": "code2-1"

}

]

}

]

}

在上面的示例文档中,access 是一个数组,其中每个元素都是一个权限对象,每个权限对象中包含 id、name、code 和 children 四个属性。如果一个权限有子权限,那么它的 children 属性就是一个嵌套的权限对象数组。

对于操作数据的需求,可以使用 MongoDB 的官方驱动程序或者第三方库(如 Mongoose)来操作数据。下面是一些示例代码:

  • 查询权限

  • 使用 find 方法查询权限文档,并将 access 数组返回即可。

    const collection = db.collection('permissions');

    const doc = await collection.findOne({});

    const access = doc.access;

    const collection = db.collection('permissions');

    const doc = await collection.findOne({});

    const access = doc.access;

    const collection = db.collection('permissions');

    const parentId = '1';

    const { name, code } = req.body;

    const newAccess = {

    id: '13',

    name,

    code

    };

    const result = await collection.updateOne(

    { 'access.id': parentId },

    { $push: { 'access.$.children': newAccess } }

    );

    const collection = db.collection('permissions');

    const parentId = '1';

    const { name, code } = req.body;

    const newAccess = {

    id: '13',

    name,

    code

    };

    const result = await collection.updateOne(

    { 'access.id': parentId },

    { $push: { 'access.$.children': newAccess } }

    );

    在上面的代码中,使用 updateOne 方法更新权限文档。第一个参数是一个查询条件,用于定位需要更新的文档。这里使用 access.id 来查询权限文档,找到对应的权限记录。第二个参数是一个更新操作,使用 $push 操作符将新的权限对象添加到 access.$.children 数组中。$ 符号代表数组中匹配到的第一个元素。

    • 编辑权限

    • 使用 $set 操作符更新指定权限对象的 name 和 code 属性。

    const collection = db.collection('permissions');

    const id = '1';

    const { name, code } = req.body;

    const result

    如果回答不够完整,请指出!

    希望能帮上忙