Cade Embery Cade Embery - 2 months ago 19
Node.js Question

Mongoose - Query a nested property of Schema.Type.Mixed as a specified data type (Date)

I have a schema setup in Mongoose with

var MySchema = new Schema({
data: {
type: Schema.Types.Mixed
}
});


My issue is that on this 'data' object i am storing a date value as a nested property, it all works fine until i try and do a find() query with Mongoose and search using the nested field. Because Mongoose doesn't know it is a Date it cant use the usual '$gte', '$lte' and similar operators im guessing because it sees that data as just a String.

One of my objects looks similar to this

{
title:"My object",
data:{
publishDate: "2016-07-12T05:00:48.985Z"
}


Is there anyway that i can explicitly tell Mongoose to expect the value to be a date so i can use '$gte' as an operator?

Model.find({
"data.publishDate":{
$gte:new Date()
}
})

Answer

Turns out i had to strictly type the value as a date before saving to the database. Otherwise the date operators '$gte', '$lte' etc would not work.

Solution is to do this

{
title:"My object",
data:{
 publishDate: new Date("2016-07-12T05:00:48.985Z")
}

At this point i don't believe you can type the data dynamically when running a query.