This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Difference between count() and find().count() in MongoDB
(5 answers)
Closed 4 years ago.
I need get amount of documents in db (mongodb) . I tried get this value to my var like this:
var unique = collection.find({email: email}).count();
and like this:
var unique = collection.find({email: email}).toArray();
unique = unique.length;
But when I try to see this number in console, that show me 'undefined' :/
Whats wrong?
P.S sry for my english
From the docs. It's db.collection.count. Don't use find.
Returns the count of documents that would match a find() query for the
collection or view. The db.collection.count() method does not perform
the find() operation but instead counts and returns the number of
results that match a query.
Example Usage:
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'users';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
const db = client.db(dbName);
const email = 'foo#bar.com';
const query = { email: email };
const options = {};
db.collection.count(query, options, (err, result) => {
// handle error
if (err) {
console.log(err);
}
// do something with result
console.log(result);
});
});
Here is a basic example of how count might work. I assume you are using the mongodb npm and not mongoose or other mongo wrappers like it. The way I would use this in a project is by making the connection to your mongodb its own module so that it can be reused with other queries. That way you don't have to wrap every query with a connection.
If you want to get all the docs of a collection, use:
db.collection.count
If you want to get all the docs of a collection by a field, use:
collection.find({email: email}).toArray(function (err, items) {
console.log(items.length);
})
Related
This question already has answers here:
How do I manage MongoDB connections in a Node.js web application?
(13 answers)
Closed 3 years ago.
I try to package the db connecting for more reusable.
I want to achieve like :
const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
const db = client.db(dbName);
// do something...
client.close();
})
.catch(err=>console.log(err));
Thus, I can use it to other places:
//For example
//query
mongoPromise.then((db)=>db.collection('user').find().toArray())
//insert
mongoPromise.then((db)=>db.collection('test').insert({...}))
When query or insert finished , the MongoClient will be close
At first method,I just can figure out a solution by mixing callback and promise.
Is it not good for mixing callback and promise together?
// First method
const mongoPromiseCallback =(callback)=>MongoClient.connect(url,{ useNewUrlParser: true })
.then(async(client)=>{
const db = client.db(dbName);
await callback(db);
console.log("close the client");
client.close();
})
.catch(err=>console.log(err))
mongoPromiseCallback(db=>db.collection('user').find().toArray())
.then(res=>console.log(res)));
At the other method,I try to use only promise,but I don't know
where can I close the client.
// the other method
const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
const db = client.db(dbName);
return new Promise(function(resolve, reject) {
resolve(db);
});
})
.catch(err=>console.log(err));
mongoPromise.then(db=>db.collection('user').find().toArray())
.then(res=>console.log("res"));
You can always reuse the db object you created in mongo. Here read this it'll answer the question How do I manage MongoDB connections in a Node.js web application?
Im writting a node app to log some informations in a mongo database.
Below is the snippet code that called each time i need to store log in the mongo database.
const mongo = {}
const mongo_cli = require('mongodb').MongoClient
module.exports = {
log (l) {
mongo_cli.connect(the_mongo_url, (error, client) => {
if (error) throw error;
mongo.cli = client;
mongo.db = client.db(the_database);
//insert and update operations
});
}
}
The code above work for now. I mean, I can insert and update logs already inserted at the price of one (or more) connection (s) that I never close due to my lack of control of callback functions.
So, how can i structure it better so that i can just have only one mongo_cli call to not consume too many ressources ?
I'm using the combo Express (Node.js) and Mongoose to make a REST API. I'm trying to make the login using a JWT token but I've got a problem. When I execute the following code
const mongoose = require('mongoose');
const User = mongoose.model('User');
// other code
_api.post('/login', function (req, res) {
const data = req.body;
// some data control
User.findOne({ username: data.username}, function(err, doc) {
if (hash(password) == doc.password) { // password check
myToken = generateToken(); // generating the token
doc.jwtToken = myToken; // including the generated token to the response
res.status(200).json(doc); // return the final JSON to client
}
}
}
the final JSON returned by the API doesn't have the field "jwtToken":"mygeneratedtoken" and this is strange. I included other times new fields inside a JSON with the same syntax and it worked. I tried to use a tmp variable to which I assigned the doc content (that is a javascript object) and then I added the jwtToken filed and return the tmp variable. But nothing.
Can someone explain me if there is something wrong with my code or if there is something that I need to know?
Documents returned by mongoose are immutable, and thus assignment to doc.jwtToken does not modify the object. You can either use the lean method to modify the query, or toObject to convert the document to a regular javascript object. Try:
var docObject = doc.toObject();
docObject.jwtToken = myToken;
res.status(200).json(docObject);
This question already has answers here:
How to list all MongoDB databases in Node.js?
(5 answers)
Closed 6 years ago.
I have seen answers on C# and Java but not able to find anything on NodeJs. I have tried using cmd shell in Windows to get the required output but no luck.
I am aware that the same information can be taken in Mongo shell but the requirement is to get a list within the NodeJs app.
cmd = child_process.exec('"C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongo.exe" admin ; db.getMongo().getDBNames()');
and also
var mongoServer = require('mongodb-core').Server;
var server = new mongoServer({
host: 'localhost'
, port: 27017
, reconnect: true
, reconnectInterval: 50 });
server.on('connect', function (_server) {
console.log('connected');
var cmdres = _server.command('db.adminCommand({listDatabases: 1})');
console.log("Result: " + cmdres);
}
You can use mongodb driver to get dbs as following
var MongoClient = require('mongodb').MongoClient;
// Connection url
var url = 'mongodb://localhost:27017/test';
// Connect using MongoClient
MongoClient.connect(url, function(err, db) {
// Use the admin database for the operation
var adminDb = db.admin();
// List all the available databases
adminDb.listDatabases(function(err, result) {
console.log(result.databases);
db.close();
});
});
Reference: http://mongodb.github.io/node-mongodb-native/2.2/api/
See this answer
db.admin().listDatabases
I have opened a connection to my remote mongodb ec2 instance but now am trying to retrieve data that is nested within a collection. The database has multiple collections (ie visitor, campaign, form, etc...) and has data already in it from another source. I am using node + express for the application.
1) Do I have to define a schema in my app to match the remote database or can I just query for the data and store it in an object?
mongoose schema creation
2) Actually retrieving the values within the visitor collection, can I just use dot notation to query within the visitor collection for visitor_id using:
db.find(visitor.visitor_id)
Here is the database connection code I am using if that helps
var uri = 'mongodb://xx.xxx.xx.x'
var mongoOptions = { db: { safe: true } };
db = mongoose.createConnection(uri, mongoOptions, function (err, res) {
if (err) {
console.log('ERROR connecting to: remote' + uri + '. ' + err);
} else {
console.log('Successfully connected to: remote' + uri);
}
});
If you're using mongoose, then yes, you need to define a schema in your app to match the database.
That notation won't work. If I understand the specific query you're trying to make (to fetch the document matching a visitor_id) then you'll need something roughly like this:
// Assuming you already have mongoose connected to the database elsewhere
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var visitorSchema = new Schema({
visitor_id: Number,
etc: etc // the rest of your schema
});
var Visitor = mongoose.model('Visitor', visitorSchema);
Visitor.findOne({ visitor_id: the_id_you_want_to_query }, function (err, doc) {
// doc contains the visitor document, if found
});
I suggest you familiarize yourself with queries with MongoDB and mongoose in particular—the docs aren't super easy to understand but cover most of the main cases.