2

I am using Mongoose.js 4.11.6 Node.js 6.0.

I have a user document which looks like bellow -

var UserSchema = new Schema({
  name: { type: String, default: '' },
  email: { type: String, default: '' },
  phone: { type: String, default: '' },
  hashed_password: { type: String, default: '' },
  role: { type: String, default: '' },
  created_at: { type: Date, default: Date.now }
});

I am running following mongoose query -

UserSchema.find({ role: options.role }) .select(options.select) .sort({ 'email': -1 }) .exec(cb);

Ideally this should return the list matching user sorted by email id. The query works exactly what it is expected to do in our AWS deployment. But in the Cosmos DB MongoDB hosting it is returning the empty resultset. But the query return results (but not in desired order) when the .sort({ 'email': -1 }) is removed.

2
  • Have you tried just passing '-email' as sort parameter? Commented Aug 9, 2017 at 13:48
  • Have you opted into proper range indexing for the email? You can't do sorts on strings without setting the precision appropriately Commented Aug 9, 2017 at 16:13

2 Answers 2

1

as discussed in a separate thread this does indeed work. Below is the complete sample code showing sorting working as expected with CosmosDB & the Mongo API via Mongoose.

https://gist.github.com/m-gagne/00893a32a0e4c7f593a1676ba1380e63

var mongoose = require('mongoose');

mongoose.connect('<COSMOS DB CONNECTION STRING>');

var Schema = mongoose.Schema;

var userSchema = new Schema({
  email: { type: String, default: '' },
});

var User = mongoose.model('User', userSchema, "users");

User.find({}).select(['email']).sort({ 'email': -1 }).exec(function(err, results) {
  if(err) {
    console.log("!!! ERROR !!!");
    console.log(err);
    return;
  }
  console.log(results);
});
Sign up to request clarification or add additional context in comments.

Comments

0

i'm using Cosmos Db document, has same issue with string field. Problem is when I create collection, policyIndex default was

{
                    "kind": "Hash",
                    "dataType": "String",
                    "precision": 3
                }

Hash Type is not good for order, change it to Range and working well

{
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.