2

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 Answer 1

2

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"
    ]
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

@TheTrainer Glad, i could help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.