Scaraux
Scaraux

Reputation: 4152

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 _ids 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 ?

Upvotes: 0

Views: 1273

Answers (1)

ZachB
ZachB

Reputation: 15366

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}})

Upvotes: 3

Related Questions