mongodb - Querying referenced collections using Mongoose Populate -
i'm having tricky time mongoose populate(). trying load referenced documents collection using user id.
i have user collection stored this.
{ id: "myuserid", // alphanumeric string. username: "me" sessions: [] // note deliberately empty. }
i have gamesessions collection stores game save states this:
{ id: "gamesaveidstring", // unique id userid: "myuserid", // user saved this. ("me") properties: {} // bunch of stuff tracks doing in game. }
i return object looks this:
{ id: "myuserid", username: "me", sessions: [{ id: "gamesaveidstring", properties: {} },{ id: "gamesaveidstring", properties: {} }, ...] // etc. }
i have looked @ mongoose documentation, i'm not finding clean way (that works) accomplish this. can nesting queries, find messy.
populate seems allow query collection part of existing query.
this how i'm trying accomplish query. successfully returns user object, lacking populate() queried sessions: []
array.
user.findone({_id: id}) .populate({ path: "sessions", // want data go on object select: 'properties id', // grab these fields match: {userid: id}, // userid, same 1 grabbed user with. model: "gamesession", // in collection options: {limit: 5} // not of them kthx. }) .exec(function(err, document) { res.json(document); });
i have user model
var userschema = new schema({ _id: string, username: string, sessions: { type: string, ref:'gamesession'} // never stores id of gamesession. don't want data stored in user document because saved , many sessions created. });
and game session model
var gamesession = new schema({ _id: string, userid: string, projectid: string });
to quote docs (http://mongoosejs.com/docs/populate.html) "there no joins in mongodb still want references documents in other collections. population comes in."
yes, exactly, have user id, , want grab stuff user id collection , bundle user in array called sessions. all.
what doing wrong?
thanks in advance.
Comments
Post a Comment