Romain Jouin
Romain Jouin

Reputation: 4838

JS - Passing a string to a MongoDB query

In javascript / Meteor, I am trying to build a customisable functions to return the last doc of a Mongo Collection according to a sort key.

This work when my sorting field (created-at) is hard-coded :

last_document = function(collection) {
  var query = {
    sort: {
      "createdAt": -1
    }
  };
  var last_document = collection.find({}, query).fetch()[0];
  return last_document;
};

But When I pass it in parameter, it doesn't :

dernier_document = function(collection, sort_by = "createdAt") {
  var query = {
    sort: {
      sort_by: -1
    }
  };
  var dernier_document = collection.find({}, query).fetch()[0];
  return dernier_document;
};

I am using meteor 1.4. Any idea ?

Upvotes: 1

Views: 636

Answers (1)

Steeve Pitis
Steeve Pitis

Reputation: 4443

You problem is not really to pass a string to mongodb, but to transform a variable as a Object key.

You can fix your problem in this way :

var query = {sort: {}};
query.sort[sort_by] = -1;

or

var query = { sort: { [sort_by]:-1}};

enter image description here

Upvotes: 1

Related Questions