单表数据多次查询
发布于 4 年前 作者 liuxingzhijian1320 4235 次浏览 来自 问答

实现评论的功能的数据查询,一级评论和 二级评论都在一张表里,问题:我如何做到一次查询使得二级评论数据应该在一级评论数据结构里面,前端可以直接渲染页面?

使用 mongoose的models的设计如下: const mongoose = require(‘mongoose’); const { Schema, model } = mongoose; const commentSchema = new Schema({ // 标题 title: { type: String, required: true }, // 评论人 from: { type: String, required: true }, // 回复哪一位 to: { type: String, required: false }, // 评论内容 content: { type: String, required: true }, // 父级id parentId: { type: String, required: true, default: 0 }, }, { timestamps: true }); module.exports = model(‘Comment’, commentSchema);

数据库数据如下: { “code”: 200, “message”: “查询评论列表成功”, “data”: [ { “parentId”: “0”, "_id": “5de51ea8197f5672506ec140”, “content”: “我看看吧”, “from”: “zhaohang”, “to”: “”, “title”: “尼玛 今年的天气有点冷啊”, }, { “parentId”: “0”, "_id": “5de51f1b197f5672506ec141”, “content”: “很好啊”, “from”: “admin”, “to”: “”, “title”: “尼玛 今年的天气有点冷啊”, }, { “parentId”: “5de51ea8197f5672506ec140”, "_id": “5de51fe493925772d2f35cb5”, “content”: “好像确实有点冷呢”, “from”: “alex”, “to”: “zhaohang”, “title”: “尼玛 今年的天气有点冷啊”, }, { “parentId”: “5de51ea8197f5672506ec140”, "_id": “5de5200493925772d2f35cb6”, “content”: “好像今年提前冷了啊”, “from”: “海东”, “to”: “zhaohang”, “title”: “尼玛 今年的天气有点冷啊”, } ] }

mongoose小白,跪求大神解惑!!

1 回复

nested set model,100级父子也一条简单sql出结果

回到顶部