node.js - Returning objects from mongoose model -


i have following code in user.js class:

exports.finduser = function(namein){   user.find({     name: namein   }); )}; 

how can make 'return' users found? telling me using "return" not best practice on node? think need use callbacks but, how?

this code using call function:

var user = require("../models/user.js");  user.finduser(req.params.name, function(users) {   console.log(users); }); 

in finduser don't seem providing place callback go. mongoose query returns document(s or error) callback handled.

if wanted modify finduser fit how seem 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) handed function in arguments of query (as callback), in line asynchronous nature of node. other accepted methods of handling node's non-blocking i/o events , streams, methods promises being viable if controversial.

mongoose uses callbacks in guides, has promises available.

looking @ function now, you're handing name query, , you'd returned documents callback. mongoose function has capability of doing everything:

user.find({name: req.params.name}, function(err,user) {   if (err)     throw err;   console.log(user); }); 

defining finduser may worthwhile if have lot of things play in document finduser keep dry.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -