首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用"$“选择器时无法查询MongoDB中的记录

使用"$“选择器时无法查询MongoDB中的记录
EN

Stack Overflow用户
提问于 2021-11-21 06:04:11
回答 1查看 27关注 0票数 0

在MongoDB中查询记录时,我在Mongoose中使用NodeJS时遇到了一个奇怪的问题。我有一个产品模型文件是这样的:

代码语言:javascript
运行
复制
const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
  name: String,
  brand: String,
  shorDescription: String,
  description: String,
  price: Number,
  salePercent: Number,
  rating: Number,
  color: String,
  size: [String],
});

const Product = mongoose.model("Product", productSchema);

module.exports = Product;

在控制器文件中,我的代码如下所示:

代码语言:javascript
运行
复制
const Product = require("../models/product.model");

exports.getProducts = async (req, res) => {
  const products = await Product.find({ rating: { $lte: "5" } });

  console.log(`products: ${products}`);

  res.json({
    products: products,
  });
};

Product.find({})完美工作->返回产品集合中的所有记录

Product.find({brand: "Nike"})仍然可以正常工作,->会返回所有的“耐克”产品。

奇怪的是,当我在Product.find({ rating: { $lte: "5" } })中使用$选择器时,当我有几个产品符合产品集合中的条件时,我什么也没有收到。

谁来帮帮我:((

EN

回答 1

Stack Overflow用户

发布于 2021-11-21 06:20:14

MongoDB查询运算符是类型敏感的。这里的问题是查询表达式是一个字符串("5"),但数据是一个数字(例如5)。因为类型是不可比较的,所以它们永远不会与$lte表达式匹配。

例如,对{rating: {$lte: "5"}}的查询将匹配如下文档:

代码语言:javascript
运行
复制
{rating: "5"}
{rating: "4.5"}
{rating: "25"}
{rating: ""}

但不像:

代码语言:javascript
运行
复制
{rating: 5}
{rating: 4.5}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70052216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档