How to get data from MongoDb using mongoose?

I just started learning MongoDB and mongoose. I currently have the following structure:

database -> skeletonDatabase collection -> adminLogin 

When I run db.adminLogin.find() from the command line, I get:

 { "_id" : ObjectId("52lhafkjasfadsfea"), "username" : "xxxx", "password" : "xxxx" } 

My connection (this works just adding it FYI)

 module.exports = function(mongoose) { mongoose.connect('mongodb://localhost/skeletonDatabase'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log('Conntected To Mongo Database'); }); } 

My -js -

 module.exports = function(mongoose) { var Schema = mongoose.Schema; // login schema var adminLogin = new Schema({ username: String, password: String }); var adminLoginModel = mongoose.model('adminLogin', adminLogin); var adminLogin = mongoose.model("adminLogin"); adminLogin.find({}, function(err, data){ console.log(">>>> " + data ); }); } 

My console.log() returning as >>>>

So what am I doing wrong here? Why am I not getting any data in my console log? Thanks in advance for any help.

+9
javascript mongodb mongoose express
source share
3 answers

mongoose by default accepts the names of singular models and maps them to a plural collection, so mongoose looks in db for a collection called "adminLogins" that does not exist. You can specify the name of your collection as the 2nd argument when defining your schema:

 var adminLogin = new Schema({ username: String, password: String }, {collection: 'adminLogin'}); 
+23
source share

first compile only one model using the circuit as an argument

var adminLogin = mongoose.model('adminLogin', adminLogin);

adminLogin does not exist in your code, adminLoginModel does;

after that instead

 adminLogin.find({}, function(err, data){ console.log(">>>> " + data ); }); 

try it

 adminLogin.find(function (err, adminLogins) { if (err) return console.error(err); console.log(adminLogins); 

"s" is important because mongo uses the plural of the model to name the collection, sorry for my english ...

+1
source share

I had a problem embedding it in the express route for my API, so I changed it thanks to @elkhrz, first defining the scheme, and then compiling one model, which I want to pull out like this:

 app.get('/lists/stored-api', (req, res) => { Apis.find(function(err, apis) { if (err) return console.error(err); res.send(apis); }); }); 

I would not send it to the body, I would actually do something else with it, especially if you plan to make your API a working application.

Go through this problem and read about the possible right ways to visualize your data. How to transfer data between routes in Express

It is always a good idea to practice safe procedures when processing data.

0
source share

All Articles