You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose使用findOne查询同一iduser对应全部操作记录实现方法

代码调整方案

1. 核心逻辑说明

Mongoose 中的 findOne 方法本身仅会返回匹配查询条件的第一条文档,无法直接返回多条匹配记录,正常查询多记录的标准方法是使用 find。如果强制要求必须使用 findOne 关键字,需要配合聚合管道将所有匹配记录封装到单条文档的数组字段中,该方案无性能优势,非必要不推荐使用。

2. 后端接口代码修正

你现有代码存在三个问题:

  • 查询方法使用错误,findOne 只能返回单条数据
  • 查询条件字段名错误,你Schema中定义的存储用户ID的字段为iduse,不是ids
  • 变量拼写错误,传递给模板的ponts是points的笔误

修正后代码:

router.get('/result', auth, async(req, res) => {
    try {
        // 统一类型,和数据库iduse字段的存储格式对齐
        const userId = req.session.user._id.toString()
        // 用find方法返回所有匹配的记录数组
        const points = await model.find({ iduse: userId })
        res.render('./options/result', {
            notes: points,
        })
    } catch (err) {
        console.error('查询数据失败:', err)
        // 查询出错时返回空数组避免前端渲染报错
        res.render('./options/result', { notes: [] })
    }
});

3. 前端EJS模板修正

原有模板部分属性没有加数组下标[i],无法正确遍历对应索引的记录,修正后代码:

<% for (var i = 0; i < notes.length; i++) { %>
<div class="child">
    <div class="itms sld1">
        <%= notes[i].objectif %>
    </div>
    <div class="itms sld">
        <%= notes[i].time %>
    </div>
    <div class="itms sld">
        <span>
            <%= notes[i].date %>
        </span>
    </div>
    <div class="itms sld">
        <%= notes[i].day %>
    </div>
    <div class="itms sld">
        <%= notes[i].level %>
    </div>
</div>
<% } %>

强制使用findOne的特殊实现方案

如果业务要求必须使用findOne关键字,可通过聚合管道将所有匹配记录打包到单条文档的数组字段中,示例代码:

router.get('/result', auth, async(req, res) => {
    try {
        const userId = req.session.user._id.toString()
        const aggregateResult = await model.aggregate([
            { $match: { iduse: userId } },
            // 将所有匹配记录打包到records数组中
            { $group: { _id: null, records: { $push: "$$ROOT" } } }
        ])
        // findOne取聚合结果的第一条,取出records数组就是所有匹配记录
        const result = await model.findOne({ _id: aggregateResult[0]._id })
        res.render('./options/result', {
            notes: result.records,
        })
    } catch (err) {
        console.error('查询数据失败:', err)
        res.render('./options/result', { notes: [] })
    }
});

内容的提问来源于stack exchange,提问作者JANATI MOHAMMED

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:36:03