I have the following code in my User.js class:
exports.findUser = function(nameIn){
User.find({
name: nameIn
});
)};
How can I make it 'return' the users it found? Something is telling me that using "return" is not best practice on Node? I think I need to use callbacks but, how?
this is the code I am using to call the function:
var User = require("../models/user.js");
User.findUser(req.params.name, function(users) {
console.log(users);
});
In findUser you don't seem to be providing a place for that callback to go. The mongoose query itself also returns the document(s or error) to a callback to be handled.
If you wanted to modify your findUser to fit with how you seem to be using it:
exports.findUser = function(nameIn,callback){
User.find({name: nameIn}, function(err,user) {
if (err)
throw err;
callback(user)
});
)};
The results of mongoose's query (successful or not) are handed to the function in the arguments of the query (as a callback), which is in line with the asynchronous nature of Node. The other generally accepted methods of handling Node's non-blocking I/O are events and streams, with methods like promises being viable if somewhat controversial.
Mongoose itself uses callbacks in its guides, but also has promises available.
Looking at your function now, you're handing it the name to query, and what you'd like to do with the returned documents as a callback. The mongoose function itself already has the capability of doing everything:
User.find({name: req.params.name}, function(err,user) {
if (err)
throw err;
console.log(user);
});
Defining findUser may only be worthwhile if you have a lot of things to play with in that document that findUser will keep DRY.