How to get collection's count in MongoDB? - node.js

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);
});

Related

How to use mongoose module in node.js to get one record from mongo db

I am trying to retrieve data from MongoDB in nodejs. The items have slightly different structure ,so I do not want to use strict schema. My code is:
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const testDataSchema = new Schema({ any: {} })
const TestData = mongoose.model('my_collection_name', testDataSchema);
var url = "mongodb://myurl";
mongoose.connect(url);
mongoose.connection.once('open', function(){
console.log('connected!!!');
}).on('error', function(error){
console.log('error!!!', error);
});
TestData.findOne({}).then(function(result){
console.log('Result', result);
})
It prints:
connected!!!
Result null
The collection defenitelly has many records. What is the problem here and how to resolve it?
Try
TestData.find(function (err, products) {
if (err) {
res.send(err);
}
console.log(products);
});
also make sure that TestData is a model object

Unable to extract collection names from mongodb

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.

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.

Remove an object by an id in mongodb and mongoose

I'm getting an error on robots.remove stating robots is not defined, But I can't possibly figure out exactly why. Please help. thank you.
mongoose.connect('mongodb://localhost/robots'); //connecting to localdb
router.delete('/:id', function(req,res){
var id = req.params.id;
console.log(id);
robots.remove({_id:ObjectId(id)}, function(err, result){ //undefined??
if (err) return res.status(500).send({err: 'Error: Could not delete robot'});
if(!result) return res.status(400).send({err: 'Robot bot deleted from firebase database'});
console.log('deleted!!!');
res.send(result);
});
});
You have to load the user model first.
var robots = require('../app/models/robots');//Load the model
robots.js file should look like this:
var mongoose = require('mongoose');
var robotSchema = mongoose.Schema({
//Your schema here
});
module.exports = mongoose.model('robots', robotSchema);

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