Nodejs新手关于mongoose问题 通过“sort_id”条件查询不到数据

Nodejs新手关于mongoose问题 通过“sort_id”条件查询不到数据

在mongo shell查询db.posts.find({‘sort_id’:2})是有数据的:

{ "_id" : ObjectId("5327357e38469e4c7ee21503"),"sort_id":2,"title":"测试"}

node中通过mongoose查询没有数据返回 Model.find({‘sort_id’:2})[]

换一个查询方式

Model.find({‘title’:‘测试’})正常返回数据:

{ "_id" : ObjectId("5327357e38469e4c7ee21503"),"sort_id":2,"title":"测试"}

大家有没有遇到这种问题?求解


2 回复

Nodejs新手关于mongoose问题 通过“sort_id”条件查询不到数据

问题描述

在MongoDB Shell中,使用db.posts.find({'sort_id': 2})可以查询到数据:

{ 
  "_id" : ObjectId("5327357e38469e4c7ee21503"),
  "sort_id": 2,
  "title": "测试"
}

但是在Node.js中通过Mongoose进行同样的查询却无法获取到数据:

Model.find({'sort_id': 2})
// 返回 []

但是,使用其他字段进行查询时可以正常返回数据。例如:

Model.find({'title': '测试'})
// 返回 
// { 
//   "_id" : ObjectId("5327357e38469e4c7ee21503"),
//   "sort_id": 2,
//   "title": "测试"
// }

解决方案

这种情况可能是因为sort_id字段的类型不匹配或定义不正确。我们需要确保在Mongoose模型中正确地定义了sort_id字段。

假设你的Mongoose模型定义如下:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const postSchema = new Schema({
  sort_id: Number, // 确保这里定义的是Number类型
  title: String
});

const Post = mongoose.model('Post', postSchema);

module.exports = Post;

接下来,检查查询逻辑是否正确。你可以尝试使用严格模式来确保查询条件的准确性:

const Post = require('./models/post'); // 假设这是你的模型文件路径

Post.find({ sort_id: 2 })
  .then(posts => {
    console.log(posts); // 应该输出查询到的数据
  })
  .catch(err => {
    console.error(err);
  });

如果仍然无法查询到数据,可以考虑以下几点:

  1. 检查数据库中的数据:确认sort_id字段确实为数字类型。
  2. 调试日志:打印出查询条件,确认传入的值是否正确。
  3. 确保连接:确认Mongoose已成功连接到MongoDB。

通过以上步骤,你应该能够解决这个问题。


根据你的描述,在Mongoose中使用Model.find({ 'sort_id': 2 })查询不到数据,而直接在Mongo Shell中查询是能查到数据的。这种情况通常是因为数据类型不匹配或者字段名问题。

可能的原因及解决方案

  1. 数据类型不匹配

    • 确认sort_id字段的数据类型是否为数字。如果在MongoDB中sort_id是数字,而在Node.js代码中却传入了字符串,那么查询结果会为空。
    • 示例代码:
      Model.find({ sort_id: 2 }) // 使用数字
      
    • 而不是:
      Model.find({ sort_id: '2' }) // 使用字符串
      
  2. 字段名问题

    • 确认字段名是否完全一致。比如是否有拼写错误或额外的空格。
    • 确保在Mongoose模型定义中字段名也是一致的。
    • 示例代码:
      const PostSchema = new mongoose.Schema({
        sort_id: Number,
        title: String
      });
      
      const Model = mongoose.model('Post', PostSchema);
      
  3. 索引问题

    • 如果没有为sort_id字段创建索引,可能会导致查询效率低或者查询不到数据。可以在模型定义时添加索引:
      const PostSchema = new mongoose.Schema({
        sort_id: { type: Number, index: true },
        title: { type: String, index: true }
      });
      
  4. 数据迁移问题

    • 确认数据是否正确迁移到了Node.js应用中。可能数据在插入数据库时没有正确更新或格式化。

示例代码

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema({
  sort_id: { type: Number, index: true },
  title: String
});

const Model = mongoose.model('Post', PostSchema);

// 连接数据库
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });

// 查询数据
Model.find({ sort_id: 2 }, (err, docs) => {
  if (err) console.error(err);
  else console.log(docs);
});

通过以上步骤排查问题,应该可以找到并解决数据查询不到的问题。

回到顶部