Wednesday, 15 June 2011

node.js - Combine Mongo Output with Node for API -



node.js - Combine Mongo Output with Node for API -

i''m new node have nodejs / express open source cms , output api info app working. forgive me if i'm not using right terminology or whatnot, new me.

what have 2 collections, locations , tours. cms allows me create relationship between two. stores array of objectid's in locations record each associated tour record.

what want take api output code (below) , have output entire tours array, finish fields (title, description, etc), in each location record. outputs array of id's.

here current code:

var async = require('async'), landmark = require('keystone'); var location = keystone.list('location'), tour = keystone.list('tour'); /** * list locations */ exports.list = function(req, res) { location.model.find(function(err, items) { if (err) homecoming res.apierror('database error', err); res.apiresponse({ locations: items }); }); } /** * location id */ exports.get = function(req, res) { location.model.findbyid(req.params.id).exec(function(err, item) { if (err) homecoming res.apierror('database error', err); if (!item) homecoming res.apierror('not found'); res.apiresponse({ location: item }); }); }

current api output (truncated):

{ "locations": [ { "_id": "53a47997ebe91d8a4a26d251", "slug": "test-location", "lastmodified": "2014-06-20t20:19:14.484z", "commonname": "test location", "__v": 3, "url": "", "tours": [ "53a47963ebe91d8a4a26d250" ], "images": [] } ] }

what i'm looking for:

{ "locations": [ { "_id": "53a47997ebe91d8a4a26d251", "slug": "test-location", "lastmodified": "2014-06-20t20:19:14.484z", "commonname": "test location", "__v": 3, "url": "", "tours": [ { "_id": "53a47963ebe91d8a4a26d250", "title": "my test tour title", "url": "url_to_audio_file" } ], "images": [] } ] }

anyone know if possible? help appreciated! thanks!

it looks have setup location model have reference tours, defined array of tours. means when store tour within location, you're not storing info represents tour, instead id references tour. when perform find operation, you're seeing in response send client.

if case, might want take @ mongoose's populate function. take references , populate them info contain.

so instance, can alter query following:

location.model.find().populate('tours').exec(function(err, items) { // items should contain populated tours }

let me know if isn't mean , can seek help further.

node.js mongodb asynchronous express keystone.js

No comments:

Post a Comment