node.js - Recover an object requested with MongoDB Driver on node JS -
i try recover object mongo db database, in node js file , doesn't work.
in file called db.js , have made following code :
var mongoclient = require('mongodb').mongoclient; module.exports = { findincoladsl: function() { return mongoclient.connect("mongodb://localhost/sdb").then(function(db) { var collection = db.collection('scollection'); return collection.find({"type" : "adsl"}).toarray(); }).then(function(items) { return items; }); } };
and, try use in file server.js :
var db = require(__dirname+'/model/db.js'); var collection = db.findincoladsl().then(function(items) { return items; }, function(err) { console.error('the promise rejected', err, err.stack); }); console.log(collection);
in result have "promise { }". why ?
i want obtain object database in order manipulate in others functions situated in server.js file.
then then
function called on promise
s returns promise
. if value returned within promise
, object promise
evaluates promise
resolves value returned. take @ this question full explanation of how works.
if want verify code getting items, have restructure code account the structure of promise
s.
var db = require(__dirname+'/model/db.js'); var collection = db.findincoladsl().then(function(items) { console.log(items); return items; }, function(err) { console.error('the promise rejected', err, err.stack); });
that should log items after retrieved database.
promises work way make working asynchronously more simple. if put more code below collection code, run @ same time database code. if have other functions within server.js file, should able call them within body of promise
s.
as rule, remember promise
return promise
.
Comments
Post a Comment