Monday 29 April 2019

Querying subdocuments mongoose

How would I query a subdocument in mongoose? const userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true, trim: true } sessions: [ { ip: { type: String }, token: { type: String }, browser: { type: String }, os: { type: String }, date: { type: Date } } ] });Let's say there a schema like this where I store the sessions of users and along with a token, if the user is accessing from same ip, browser and os, I give him the same token, if not I create a new token and supply him. In order to achieve that, I need to query a subdocument with the information I know but right now, I guess there isn't a method to do it?I could do,User.findOne({email: email, 'sessions.ip': ip, 'sessions.browser': browser, 'sessions.os': os}).then(user => {});That would just give me the user document but how would I give the user his ip until I get the specific subdocument?Should I just use filter or for..loop on the user document or is there a better way to do it? Thanks. (I know the process maybe flawed but right now I am just worried about querying the subdocuments)Found a solution, not yet 100% sure, but this works, User.findOne( { email }, { sessions: { $elemMatch: { ip: userAgent.ip, browser: userAgent.browser, os: userAgent.os } } } ) .then(user => { res.json({ user: user.sessions[0].token }); })

Submitted April 29, 2019 at 12:49PM by sum__sleples

No comments:

Post a Comment