node.js - How to find a latest data in array in mongoose -


i have conversation model below:

const convoschema = mongoose.schema({     convoid: {         type: string,         required: true     },     seller: {         type: string,         required: true     },     buyer: {         type: string,         require: true     },     product: [{ type: schema.types.objectid, ref: 'post' }],     messages: [{ type: schema.types.objectid, ref: 'message' }] }) 

and i'm trying latest message in convo couldn't figure out how it. ideas?

_id contains timestamp in it, first element in .find() oldest , last element newest,

so adding sort like: { _id: -1} give u latest data

var convo = mongoose.model('convo', convoschema); //init mongoose model  convo.find()      .limit(1)      .sort({ _id: -1 }) 

you can remove .limit() if u want complete list of documents

=======================================================================

sorry not reading properly,

for latest message,

convo.findone({}, response => {    var data = response.toobject();    latestmessage = data.messages.pop() }) 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -