Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose error Unsupported projection option: sort: { createdAt: -1 }

I'm trying to sort my mongoose entries by date, most recent first in node.js express with mongoose.

the mongoose query is:

  FecalRequest.findOne({uid: req.user.id}, {sort:{'createdAt':-1}}, (err, fecalkits) => {
    console.log(fecalkits);
    done(err, respiratorykits, fecalkits)
  });

I've tried both created_at and createdAt. The error is eMongoError: Unsupported projection option: sort: { createdAt: -1 }

For reference, the FecalRequest model looks like:

const fecalSchema = new mongoose.Schema(
  {
    uid: String,
    email: String,
    status: {type: String, default: 'No Request' },
  },
  { timestamps: true });

I just want to return the most recently made entry for a particular user.

like image 539
ingrid Avatar asked Nov 30 '22 16:11

ingrid


2 Answers

Include an empty object as a second (projection) parameter so that your third parameter to findOne is properly interpreted as query options:

FecalRequest.findOne({uid: req.user.id}, {}, {sort:{'createdAt':-1}}, (err, fecalkits) => {
  console.log(fecalkits);
  done(err, respiratorykits, fecalkits)
});

Definitely the most times I've used the word "fecal" in an answer.

like image 76
JohnnyHK Avatar answered Dec 03 '22 04:12

JohnnyHK


You wouldn't use findOne for this. You'd use find() with sort() and limit().

findOne is just going to return the first document found that matches your search criteria.

like image 35
Wake Avatar answered Dec 03 '22 05:12

Wake