猫鼬查找不返回任何文档,而指南针

时间:2020-05-25 14:27:07

标签: node.js mongodb express mongoose

目标

使用mongoose.find从mongoDB'产品'集合中按类别ID获取产品

期望的和实际的结果

所有具有匹配类别的文档应以限制数返回,但我收到一个空数组。 我尝试使用mongodb的指南针进行查询-它按预期工作。我什至尝试使用我的代码使用id(有效),title(有效)和price(无效)查找文档。找不到问题根的开头。

代码

产品架构和模型:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  thumbnail: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  category: {
    type: mongoose.Types.ObjectId,
    required: true,
  },
  rating: {
    type: Number,
    default: 0,
  },
  voters: {
    type: Number,
    default: 0,
  },
});

.
.
.

const Product = mongoose.model('product', productSchema);

module.exports = { Product, ... };

解析器:

products: (_, { limit, category }) => {
      console.log(mongoose.Types.ObjectId('5ec120a9fc13ae248f000004')); // Works fine
      Product.find({ category: mongoose.Types.ObjectId(category) }) // Tried also as a simple string, still not working
        .limit(limit)
        .exec((err, products) => {
          if (err) console.log(err);
          console.log(products);
        });
      if (category) return Product.find({ category }).limit(limit);
      return Product.find({}).limit(limit);
    },

结果记录在控制台中

5ec120a9fc13ae248f000004
[]

“产品”收藏样本:

{
    "_id": {
        "$oid": "5ec129e55db26438fcdb9b01"
    },
    "title": "Ecolab - Lime - A - Way 4/4 L",
    "category": "5ec120a9fc13ae248f000004",
    "thumbnail": "https://source.unsplash.com/350x390/?Automotive",
    "price": "236.13",
    "rating": 878210,
    "voters": 2668388
},
{
    "_id": {
        "$oid": "5ec129e55db26438fcdb9b02"
    },
    "title": "Mushrooms - Black, Dried",
    "category": "5ec120a9fc13ae248f000001",
    "thumbnail": "https://source.unsplash.com/350x390/?Sports",
    "price": "439.85",
    "rating": 549879,
    "voters": 2375685
},
{
    "_id": {
        "$oid": "5ec129e55db26438fcdb9b03"
    },
    "title": "Dried Figs",
    "category": "5ec120a9fc13ae248f000004",
    "thumbnail": "https://source.unsplash.com/350x390/?Automotive",
    "price": "202.60",
    "rating": 925701,
    "voters": 2740499
}

1 个答案:

答案 0 :(得分:0)

TL; DR:您必须将数据库中pricecategory字段中的数据转换为NumberObjectId

使用Mongoose查询数据时,请确保数据类型全部匹配

    您正在查询的字段的
  1. 数据类型与您的模式
  2. 匹配

通过某些操作(例如聚合,猫鼬无法轻松推断类型),猫鼬将帮助您进行转换 根据模式,但并非总是如此。最好总是 自己转换值,以避免出现类似的意外情况。

  1. 存储在数据库中的数据的数据类型实际上与您在 schema 中指定的数据匹配。

您的架构可能已更改,请确保相应地迁移和转换数据。由于猫鼬有时会为您转换值,因此,如果存储的数据与架构不匹配,它将与您尝试查询的内容不匹配。

从您的数据库输出中,我们可以推断出"price": "236.13""category": "5ec120a9fc13ae248f000004"的存储为Strings而不是应该的NumberObjectId。我们可以从"rating": 878210"_id": { "$oid": "5ec129e55db26438fcdb9b01" }看到NumberObjectId的表示方式。