Unable to extract collection names from mongodb - node.js

I have a mongodb (simple_demo) with an employee collection inside.
I am trying to connect to node JS and list the collections inside the simple_demo db.
I tried doing this but nothing came back. it just shows [].
Am wondering if I did anything wrong?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/simple_demo');
var db = mongoose.connection;
db.on('open', function () {
console.log("connection ok");
db.db.listCollections().toArray(function (err, names) {
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
});
});

Good day
Your code works. Check your database.

Related

How to get collection's count in MongoDB?

this is my code
var mongoose = require('mongoose');
db = mongoose.createConnection('mongodb://localhost/myDB');
there is collection users in myDB, how can i get number of documents in users?
Have you even tried to do this yourself?
None the less,
db.open (function(error){
db.collection("users", function(error, collection){
collection.count({}, function(error, numOfDocs) {
console.log(numOfDocs + ' total users');
});
});
});
That should get you started, I ahven't tested this code but I remember doing it like that.
try this way, its a snippet from my dummy code and it should work
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDB'); // Connect to mongodb
mongoose.connection.once('open',(db)=>{ // opens the connection for us
console.log("Connection made to mongodb");
mongoose.model('<collection>').count().then((count) => { // replace <collection> with collection name
console.log(count);
})
}).on('error',(error)=>{
console.log("connection error to mongodb : " + error);
});

Node Express Mongodb connection syntax and error handling

I was having an issue in my app that was simply from an oversight on the database name that I provided to my mongodb connection. While looking around I ran across the examples here:
https://wesleytsai.io/2015/08/02/mongodb-connection-pooling-in-nodejs/
So my question is why don't I get any kind of error thrown if I am providing a database that does not exist to the mongodb connection? I just need help interpreting/understanding the syntax below. On this line:
MongoClient.connect(mongoUrl, function(err, database) {
if( err ) throw err;
.
.
.
shouldn't an error be thrown since mongo can't connect if the database doesn't exist?
What I'm trying to do is setup some kind of error handling that can flag the fact the the database doesn't exist and likewise with the collection if that too does not exist ('expenses' should be 'test').
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var mongoUrl = 'mongodb://127.0.0.1:27017/expenses';
var db;
exports.connect = function(callback) {
MongoClient.connect(mongoUrl, function(err, database) {
if( err ) throw err;
db = database;
callback();
})
}
In mongodb, if you are connected to the datbase and then you provide a schema to a collection that you defined, then irrespective of the fact that whether that collection is there or not, mongodb creates a collection for you.
For example if you have the following code,
module.exports = mongoose.model('User', schema);
a collection named users is created in the database. So even if you dont have a collection, mongodb will create one for you.
If you want to check whether a database exists then follow like below:
var mongoose = require('mongoose')
, Admin = mongoose.mongo.Admin;
/// create a connection to ypur database
var connection = mongoose.createConnection(
'mongodb://user:password#localhost:port/your_database');
connection.on('open', function() {
// connection successful
new Admin(connection.db).listDatabases(function(err, result) {
console.log('listDatabases successful');
// the database lists are stored in result.databases
var allDatabases = result.databases;
// allDatabases contains the record of all the databases
// crosscheck this list with the database you want
});
});

Find() Method MongoDB with Nodejs

I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.
When I try to run this I get:
"TypeError: Cannot read property 'find' of undefined" error return.
If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.
module.exports = function(app, db) {
app.get('/foo', (req, res)=>{
db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
};
Thanks
Paul is right, there is some issue in your code which is why it's returning null.
Here try this snippet. I'm using 2 files for demo.
model.js
const mongoose = require('mongoose');
mongoose.connect('mongo_url');
var barSchema = new mongoose.Schema({
// your schema
});
module.exports = mongoose.model('Bar', barSchema);
main.js
var BarCollection = require('./models'); // assuming both files are in same directory.
BarCollection.find({foo: {$all: ['bar']}}
,(err, item)=>{
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
};
Basically what I am trying here is:
separate MongoDB model code in separate files
Import mongo collection in API files for CRUD operations
db.collection('barCollection') is returning null for some reason. You'll need to figure out why, it's probably somewhere else in your code since you don't have the setup logic here.
I'd look at whether mongodb was connected properly (i.e. is the db instance you're passing that function actually connected to the database), is mongodb running and available on the port you configured it with, etc.

Mongoose findById is returning null

So I have this schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TreeSchema = new Schema({
}, { collection: 'treeLocations' });
var TreeDetailsSchema = new Schema({
}, { collection: 'treeInfo' });
module.exports = mongoose.model('Tree', TreeSchema);
module.exports = mongoose.model('TreeDetail', TreeDetailsSchema, "treeInfo");
And I am calling by ID like this:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
router.route('/api/trees/:tree_id')
.get(function(req, res) {
TreeDetails.findById(req.params.tree_id, function(err, treedetail) {
if (err)
res.send(err);
res.json(treedetail);
});
});
For some reason - http://localhost:3000/api/trees/5498517ab68ca1ede0612d0a which is a real tree, is returning null
Something that might help you help me:
I was following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
The only thing I can think of that changed is that I have a collection name. Might that be it?
The step that I don't see is how you actually connect to MongoDB and after that, how you get the Model from the connection.
// connect to MongoDB
var db = mongoose.createConnection('mongodb://user:pass#host:port/database');
// now obtain the model through db, which is the MongoDB connection
TreeDetails = db.model('TreeDetails');
This last step is how you associate your model with the connected mongo database.
More info on Mongoose.model
There are several ways to establish a connection to MongoDB with mongoose, the tutorial uses:
mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o');
(Personally I prefer the more explicit mongoose.createConnection as shown in the example)
(I used mongoose 4.3.1 for this example)
My steps to reproduce, in order to provide a working example (without creating a webservice for it):
var mongoose = require('mongoose'),
TreeDetails, db;
// create the model schema
mongoose.model('TreeDetails', mongoose.Schema({
// .. your field definitions
}, {collection: 'treeInfo'}));
db = mongoose.createConnection('mongodb://user:pass#host/example');
TreeDetails = db.model('TreeDetails');
TreeDetails.findById('5671ac9217fb1730bb69e8bd', function(error, document) {
if (error) {
throw new Error(error);
}
console.log(document);
});
Instead of:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
try:
var mongoose = require('mongoose'),
TreeDetails = mongoose.model('TreeDetail');
Defining the collection name shouldn't give you any issues. It's just what the collection will be called in the database / when using the mongo shell.
And just to be sure, try logging req.params.tree_id before calling findById to make sure it's coming through as you suspect.

mongodb + mongoose: query not entering .find function

I am getting start with mongodb and mongoose but am having problems querying a database. There are a number of tutorials online for what I am trying to do but it just doesn't seem to work for me. My problem is that the .find() function is not even being called and the collection is not being displayed. I have a collection called Subjects in which I know there are some values (I manually entered them in the mongodb command line). I only tried including pertinent code but let me know if anything else is needed. Thanks in advance.
app.js file
require('./models/model.js');
var conn = mongoose.createConnection('mongodb://localhost/test');
var Subject = mongoose.model('Subjects');
Subject.find( { }, function (err, subjects) {
if(err) console.log("Error"); // There is no "Error"
console.log("Made it"); // There is no "Made it"
console.log(subjects);
});
model.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectsSchema = new Schema ({
subject: { type: String }
});
module.exports = mongoose.model('Subjects', SubjectsSchema);
Call mongoose.connect instead of mongoose.createConnnection to open the default connection pool that will be used by models created using mongoose.model:
mongoose.connect('mongodb://localhost/test');

Resources