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

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -