Mongodb : find documents including references to sub-documents [node-mongodb-native] -
i have following mongodb documents :
users : {'_id' : '12345', 'fullname' : 'abc'} , files : {'_id' : 'file001', 'path' : 'patha', 'users_id' : '12345'} {'_id' : 'file002', 'path' : 'pathb', 'users_id' : '12345'}
how query or find 'files' documents in way 'users_id' referencing 'users' document has full 'users' document?
expected output :
{'_id' : 'file001', 'path' : 'patha', 'users_id' : '12345', 'user' : {'_id' : '12345', 'fullname' : 'abc'}} {'_id' : 'file002', 'path' : 'pathb', 'users_id' : '12345', 'user' : {'_id' : '12345', 'fullname' : 'abc'}}
in way, access file owner's fullname such : file.user.fullname
i appreciate guys. thank you.
--- edit
i using node-mongodb-native access db.
below code retrieve it:
var files = db.collection ('files'); files.find ({}, {}).toarray (function ( err, filesdoc){ ( var index in filesdoc) { var filedoc = filesdoc [ index ]; var users = db.collection ('users'); users.findone ({'_id' : filedoc.users_id}, {}, function (erruser, userdoc){ if ( ! erruser ) { filedoc.user = userdoc; } }); } });
but code not assigning user files doc , assigns last element of filesdoc array. suggestions?
mongodb doesn't support joins have query user details separately. if you're using node.js, mongoose provides populate
feature simplify can following pull in user details:
files.find().populate('users_id')
Comments
Post a Comment