I'm using this syntax to filter documents
const query = Model.find();
const filters = req.body;
if(filters.someValue){
query.find().where('someValue').eq(filters.someValie);
}
...(imagine 40 more)
before i execute this query to find all the documents, i want to sort it by a specific order which i will determine
if(filters.sort){
here the sort need to be applied - before execution.
}
i got some field in the DB with four optional values, and i want to attach order to each value (the sort needs to be applied by that). lets say the values can be:
"A", "B", "C", "D"
the order i want the documents to be sorted by:
{value:"A",order:3}, {value:"B", order:2}, {value:"C", order:4}, {value:"D", order:1}
and after the sort is apply - execute the query. the problem is that i could not find anything about this online, and the only thing i tried (Aggregate with sort and condition) - didn't work. the code:
SomeModel.aggregate([
{ "$project" : {
"document": "$$ROOT",
"order" : {
"$cond" : {
if : { "$eq" : ["$someField", "D"] }, then : 1,
else : { "$cond" : {
"if" : { "$eq" : ["$someField", "B"] }, then : 2,
else : { "if" : { "$eq" : ["$someField", "A"]}, then: 3,
else : { "if" : { "$eq" : ["$someField", "C"]}, then: 4
}
}
}
}
}
}
}},
{"$sort" : {"order" : 1} }
]);