I'm new to Node.JS and can't find a solution to this. I'm building a restful 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've tried many different approaches. But always get this as result:
{
options: {
populate: { }
},
_conditions: { },
_updateArg: { },
op: "find"
}
but my console.log(metadatas); line is printing the results to the console. I'm using all the latest packages. Can somebody help me?
You can't really mix synchronous return
s with asynchronous functions like findById
, as it goes against the basic nature of asynchronous operations: "exit now, complete later."
You'll have to adjust getMetadata
to accept a callback function that can be called when findById
has completed later:
exports.getMetadata = function (id, callback) {
// ...
};
And, instead of returning metadatas
only when there's not an err
:
if (!err) {
return metadatas;
} else {
// ...
}
You'll want to call the callback
in either case:
callback(err, err ? null : metadatas);
In context, that could be:
FolderInfo.find({}, null, null, function (err, metadatas) {
if (err) {
console.log(err);
} else {
console.log(metadatas);
}
callback(err, err ? null : metadatas);
});
Or possibly just:
FolderInfo.find({}, null, null, callback);
Then pass getMetadata
a callback function that handles the response when called:
app.get('/metadata', function(req, res) {
console.log("GET: metadata");
database.getMetadata(null, function (err, data) {
res.send(data);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With