my mongodb version 3.2, mongoose version 4.6.0
these schemas:
// chat const chatschema = new mongoose.schema({ users: [{ type: mongoose.schema.types.objectid, ref: 'user', required: true }], lastmessage: { type: mongoose.schema.types.objectid, ref: 'message' } }); export const chatmodel = mongoose.model('chat', chatschema); // message const messageschema = new mongoose.schema({ user: { type: mongoose.schema.types.objectid, ref: 'user', required: true }, chat: { type: mongoose.schema.types.objectid, ref: 'chat', required: true }, text: { type: string, required: true }, timestamp: { type: date, default: date.now } }); export const messagemodel = mongoose.model('message', messageschema);
i want sort based on lastmessage's timestamp in desc order. tried these three
chatmodel .find({}, 'lastmessage') .populate('lastmessage', 'timestamp', null, { sort: { timestamp: -1 }}) .exec() .then(chats => console.log(chats)) chatmodel .find({}, 'lastmessage') .populate({ path: 'lastmessage', select: 'timestamp', options: { sort: { timestamp: -1 }} }) .exec() .then(chats => console.log(chats)) chatmodel .find({}, 'lastmessage') .populate('lastmessage', 'timestamp') .sort({ 'lastmessage.timestamp': -1 }) .exec() .then(chats => console.log(chats))
also, no matter use -1
or 1
, 'desc'
, or 'asc'
timestamp
, gives me same results:
[{ _id: 57c8a682cde8baf5c36eb1fc, lastmessage: { _id: 57c8baa29a293eace7f9be15, timestamp: 2016-09-01t23:32:50.344z } }, { _id: 57c8a6d0cde8baf5c36eb1fe, lastmessage: { _id: 57c8fabb4362b3c25d828774, timestamp: 2016-09-02t04:06:19.421z } }]
what may cause this? thanks
update1:
it seems bug of mongoose.
please track this issue on github.
update2: said not supported. don't know why... using sort
in populate
wrong case?
try this..
chatmodel .find({}) .populate('lastmessage', 'timestamp', { options: { sort: { 'lastmessage.timestamp': 'desc' } } }) .exec() .then(chats => console.log('chats', chats))
Comments
Post a Comment