首页 > 解决方案 > 使用猫鼬进行高级搜索

问题描述

我有一个查询对象

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,

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

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

标签: databasemongodbmongoosesearch

解决方案


尝试这个

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

推荐阅读