Server-side sorting using Mongoose (mongodb + node.js)

I am trying to sort based on function. I am currently doing the following and it works.

var _criteria = ... some search criteria var _pageNumber = ... the page num I want to see var _nPerPage = ... the number of documents per page var _sort = {}; _sort.name = ... the column name I am sorting on _sort.order = ... asc or desc sort Collection.find(_criteria) .skip((_pageNumber-1)*_nPerPage) .limit(_nPerPage) .sort(_sort.name,_sort.order) .execFind(function (err, docs) { ... }); 

Now, I would like to sort based on some function that accepts user input:

 var sortFunc = function(x){ return (x - doc.score); }; // where doc.score is an attribute of the document I am searching on // and x is a user provided value 

and I can’t find a way to do this. I tried to evaluate this function as follows:

 var mongoose = require('mongoose'); var mdb = mongoose.connect(uri); var myfunc = function(x){ return x; }; mdb.connection.db.eval( myfunc, "asdf", function (err, retval) { console.log('err: '+err); console.log('retval: '+retval); }); 

but I get the following error:

 err: Error: eval failed: db assertion failure retval: null 

Any help on this would be awesome. Thank you very much

0
source share
1 answer

I think you need to do this:

 var mongoose = require('mongoose'); mongoose.connect(uri); mongoose.connection.on("open", function(err){ mongoose.connection.db.eval("function(x){ return x; }", "asdf", function (err, retval) { console.log('err: '+err); console.log('retval: '+retval); }); }); 

This may work on my pc. You need to make sure the connection is available.

+1
source

Source: https://habr.com/ru/post/946732/


All Articles