Node.js: Failed to return Mongoose search results

I am new to Node.JS and cannot find a solution to this. I am creating a sedative service to retrieve data from mongo.

app.js

var database = require('./database.js'); ... app.get('/metadata', function(req, res) { console.log("GET: metadata"); res.send(database.getMetadata(null)); }); app.get('/metadata/:id', function(req, res) { console.log("GET: metadata"); res.send(database.getMetadata(req.params.id)); }); ... 

database.js

 exports.getMetadata = function (id) { console.log('getting metada...') if (id == null) { return FolderInfo.find({}, null, null, function (err, metadatas) { if (!err) { console.log(metadatas); return metadatas; } else { return console.log(err); } }); } else { return FolderInfo.findById(id, function (err, metadatas) { if (!err) { return metadatas; } else { return console.log(err); } }); } } 

I have tried many different approaches. But always get this as a result:

 { options: { populate: { } }, _conditions: { }, _updateArg: { }, op: "find" } 

but my console.log (metadata); line prints the results to the console. I use all the latest packages. Can someone help me?

+4
source share
1 answer

You cannot mix synchronous return with asynchronous functions such as findById , as this contradicts the basic nature of asynchronous operations: "exit now, finish later".

You will need to configure getMetadata to accept the callback function, which can be called when findById completed later:

 exports.getMetadata = function (id, callback) { // ... }; 

And instead of returning metadatas only when err does not exist:

 if (!err) { return metadatas; } else { // ... } 

You want to call callback anyway:

 callback(err, err ? null : metadatas); 

In the context, this may be:

 FolderInfo.find({}, null, null, function (err, metadatas) { if (err) { console.log(err); } else { console.log(metadatas); } callback(err, err ? null : metadatas); }); 

Or maybe just:

 FolderInfo.find({}, null, null, callback); 

Then pass getMetadata a callback function that processes the response when called:

 app.get('/metadata', function(req, res) { console.log("GET: metadata"); database.getMetadata(null, function (err, data) { res.send(data); }); }); 
+9
source

All Articles