【问题标题】:Advanced search with mongoose使用猫鼬进行高级搜索
【发布时间】:2021-10-05 09:04:12
【问题描述】:

我有一个查询对象

const query = {
brand : BMW,
yearFrom : 2000,
yearTo : 2003,
price : 7000,
};

我试图找到包括 2000 年至 2003 年之间制造的每辆宝马。 我正在尝试这种方式,但它不起作用

 if (query.yearFrom) {
        return  offerModel.find({query,year : {$gte : query.yearFrom  }}, function(err,arr) {console.log(err,arr)}).skip(offset).limit(12);
       
    }

这是猫鼬模式

const mongoose = require('mongoose');


const offerSchema = new mongoose.Schema({
    brand: {
        type: String,
        required: true,
    },
    model: {
        type: String,
        required: true,
    },
    year: {
        type: Number,
        required: true,
    },
    color: {
        type: String,
        required: true,
    },
    power: {
        type: Number,
        required: true,
    },
    mileage: {
        type: Number,
        required: true,
    },
    populatedState: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true,
    },
    condition : {
        type: String,
        required: true,
    },
    doors: {
        type: Number,
        required: true,
    },
    description: {
        type: String,
        required: true,
    },
    transmission: {
        type: String,
        required: true,
    },
    engineType: {
        type: String,
        required: true,
    },
    category: {
        type: String,
        required: true,
    },
    imageURLs : [],
    imageIds : [],
    creator: {
        type: mongoose.Types.ObjectId,
        ref: 'user'
    },
})




module.exports = mongoose.model('offers', offerSchema);

来自数据库的样本数据

_id:60fe98301b76642e04a31c45,
imageURLs:[],
imageIds : [],
brand:BMW,
model:335,
year:2000,
color:White,
doors:4,
power:130
mileage:30000,
populatedState:Sofia,
price:7000,
condition:Used,
description:qweqweqweqe,
transmission:Automatic gearbox,
engineType:Petrol,
category:Sedan,
creator:60fe97d11b76642e04a31c44,
__v:0,

如果我只查询它会找到品牌、型号等。但是它不能正确地搜索年份。

如果你们有一些想法我会很高兴我该如何解决这个问题 谢谢!

【问题讨论】:

    标签: database mongodb mongoose search


    【解决方案1】:

    试试这个

    offerModel.find({
          $and: [
              { brand :query.brand  },
             year : {
                $gte: query.yearTo, 
                $lt: query.yearFrom
            }
          ]
      }, function (err, results) {
          ...
      }
    

    【讨论】:

    • 返回空数组。在我上面的例子中也返回空数组
    • @zhpbg 样本数据集
    • 对不起,你什么意思?
    • 给我猫鼬模式和一些示例数据
    • 我已经编辑了帖子,因为我不能留下长的 cmets。你可以看到上面的 mongoose 架构和示例数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多