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

如何用Mongoose实现MySQL中id≠parent_id的查询操作?

用Mongoose实现等价于SELECT * FROM category where id <> parent_id的查询

嘿,这个需求我刚好处理过,来给你讲讲怎么用Mongoose实现和这条SQL完全等价的查询。

首先得明确:在MongoDB(Mongoose是它的ODM工具)里,直接比较同一个文档的两个字段不能用普通的查询语法,得借助$expr来编写字段间的比较表达式。具体实现步骤如下:

1. 确保你的Category模型已正确定义

先确认你的模型和MySQL表结构对应,大概是这样:

const mongoose = require('mongoose');

const categorySchema = new mongoose.Schema({
  id: { type: Number, required: true },
  name: { type: String, required: true },
  parent_id: { type: Number }
});

const Category = mongoose.model('Category', categorySchema);

2. 编写查询代码

方式一:Promise链式调用

Category.find({
  $expr: {
    $ne: ['$id', '$parent_id'] // $前缀代表引用当前文档的对应字段
  }
})
.then(matchingCategories => {
  console.log('符合条件的分类:', matchingCategories);
})
.catch(error => {
  console.error('查询出错:', error);
});

方式二:async/await(更简洁易读)

async function fetchNonSelfParentCategories() {
  try {
    const matchingCategories = await Category.find({
      $expr: {
        $ne: ['$id', '$parent_id']
      }
    });
    console.log('符合条件的分类:', matchingCategories);
    return matchingCategories;
  } catch (error) {
    console.error('查询出错:', error);
    throw error; // 可向上抛出错误让调用方处理
  }
}

// 执行查询
fetchNonSelfParentCategories();

关键逻辑说明

  • $expr:这个操作符允许我们在查询中使用聚合表达式,核心作用就是实现同一个文档内的字段对比,完美对应SQL里id <> parent_id的逻辑。
  • $ne:MongoDB的“不等于”操作符,功能和SQL里的<>完全一致,用来判断id字段的值是否不等于parent_id字段的值。

如果你的模型用的是MongoDB默认的_id主键(而非自定义的id),只需要把表达式里的$id换成$_id即可。

内容的提问来源于stack exchange,提问作者Arko Mandal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:22:33