Mongoose how to search array in array

Viewed 160

I have array with dates. User passes 2 dates: start and stop. I generate array with dates between these dates. Then I have to check in my model if any date from array is in that model. If there's no date (or dates) from array then I want this car, else - i don't want it. How to write whis mongoose query?

I have this model:


const CarSchema = mongoose.Schema({
    mark:{
        type: String,
        required: true,},
    model:{
        type: String,
        required: true,},
    price:{
        type: Number,
        required: true,},
    available: {
        type: Boolean,
        required: true,},
    reserved:{
        type:[Date],

    },
    pic_1:{
        type:String,
        required:true,
    },
    pic_2:{
        type:String,
        required:true,
    },


},
{ collection: 'cars' }
)

Lets suppose user passes 2 dates 12-02-2021 and 16-02-2021. My method generates array with all dates betweeen array = [12-02-2012,13-02-2021,14-02-2021 ... 16-02-2021] in my model i have field reserved - this is array as well. How to take from database only that cars which field reserved doesn't contains ANY date from array?

Car.find({??what here??});

Thanks in advance!

1 Answers

Demo - https://mongoplayground.net/p/HpliQ8Q70uM

Use $nin for - doesn't contains ANY date from array

$nin selects the documents where:

the field value is not in the specified array or the field does not exist.

db.collection.find({
  reserved: {
    $nin: [
      "12-02-2021",
      "12-04-2021"
    ]
  }
})

Demo - https://mongoplayground.net/p/ewG_6dQ1UaL

Use $in if you want to match values from array

The $in operator selects the documents where the value of a field equals any value in the specified array.

db.collection.find({
  reserved: {
    $in: [
      "12-02-2021", "12-04-2021"
    ]
  }
})
Related