简体   繁体   中英

Mongoose, get position of element in array

I am developping the messaging part of an app.

I have a schema that represents a conversation. It contains an array of ObjectId , and each ObjectId refers to a message.

I would like the user to sent to my API a message _id , so I can retrieve all the messages _id s on the array, after the one he sent. So he can update with all the messages he doesn't have yet.

I can I get the position of the _id he sends me, within the messages: [ObjectId] array, into the query ?

Mongo doesn't support this type of query on the server, so if you take this approach you will have to do it within your application.

You might want to consider other possible architectures. First, after you have the position of the last ObjectId, how will you make your subsequent query? You could instead query the messages collection directly, using the timestamp that is encoded in the _id to return only newer messages:

db.messages.find({_id: {$gt: lastViewedMessage._id}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM