I'm new to node.js and mongodb.
I'm trying to create a schema for a User collection in a mongolab mongodb database from a node.js app with the code below. The code does not seem to be failing (at least, I get no error messages), but I don't see any indication that it is succeeding either. That is, when I go to mongolab and look at my database, I don't see that any schema was created - https://dzwonsemrish7.cloudfront.net/items/01263Y1c312s233V0R17/mongodb-schema.png?v=7fdc20e3.
Can someone explain what I might be doing wrong, or how I can verify that my code succeeded and a schema was, in fact, created for my collection?
// file: app.js
var express = require('express'),
http = require('http'),
mongoose = require('mongoose');
var app = express(),
port = 3000;
// Connect to database in the cloud (mongolab)
mongoose.connect('mongodb://username:password#ds041344.mongolab.com:41344/stockmarket');
// Create a schema for User collection
mongoose.connection.on('open', function () {
console.log(">>> Connected!");
var UserSchema = new mongoose.Schema({
username: {type: String, unique: true},
password: String
});
var UserModel = mongoose.model('User', UserSchema);
});
app.get('/', function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!\n');
});
http.createServer(app).listen(port, function(){
console.log("Express server listening on port " + port + " ...");
});
You must insert a document first. Schemas are not explicitly defined in mongodb. Once you insert a document, the collection will automatically be created and you will see it in the mongolab console.
Example from http://mongoosejs.com/
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');
var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
after the save call above the collection will be created
Data in MongoDB has a flexible schema. Documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.
Related
I am trying to create web services using node js,express and mongoose.
this is my app.js file
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
GetData = require('./models/women');
mongoose.connect('mongodb://localhost/shopping');
var db = mongoose.connection;
app.get('/api/getCategories',function(req,res){
GetData.getCategory(function(err,getCategory){
if (err) {
throw err;
}
res.json(getCategory);
});
});
app.get('/',function(req,res){
res.send('Hi i am Madhura. Nice to Meet u. lets start creating web services');
});
app.listen(3000);
console.log('connected to Port 3000');
this is my women.js file
var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = module.exports = mongoose.model('',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
I am unable to understand this line
var Category = module.exports = mongoose.model('',categorySchema);
I have left this ' ' blank because I wanted to know what parameter is passed here
I watched a video about this, and could not find a conclusion. however, I simply followed the video and run the code. but my output is coming to be a null JSONArray "[]". Please tell me what am i doing wrong.
var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = mongoose.model('Category',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
The part you have made '' contains the mongoose model name that you can use to refer the respective MongoDB collection. you can imagine a model name as replacement of db.collectionname for MongoDB. I have updated the codebase
I am trying to connect mongodb to my express nodejs web application. I am fresh new to nodejs. I am following this tutorial video but I couldn't complete it due to the connection of mongodb.
the app.js code I have:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
Genre = require('./models/genre');
let conn = mongoose.connection;
conn.openUri('mongodb://localhost/bookstore');
conn.on('error', err => console.error('mongodb connection error',
err));
conn.on('connected', () => console.info(`Connected to mongodb`));
conn.on('disconnected', () => console.info('Disconnected from
mongodb'));
app.get('/', function(req, res){
res.send('Hello World');
});
app.get('api/genres', function(req , res){
Genre.getGenres(function(err, genres){
if(err){
throw err;
}
res.json(genres);
})
});
app.listen(3666);
console.log('Server Running On http://localhost:3666');
and this is the genre.js
var mongoose = require('mongoose');
var genreSchema = mongoose.Schema({
name:{
type: String,
requires: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model('Genre', genreSchema);
module.exports.getGenres = function(callback, limit){
Genre.find(callback).limit(limit);
}
and this is a picture of the database in the terminal
https://i.stack.imgur.com/S3gFb.png
And the information in genres collection in the database
https://i.stack.imgur.com/sJFE6.png
Once I open the main page I get the Hello World but once I add api/genres which I should get the data from mongodb I get this error
https://i.stack.imgur.com/B4c8o.png
and this is the files structures
https://i.stack.imgur.com/okHIN.png
I know this is a basic question but I couldnt figured out I check on google there are others way to connect to the database but I need to know why this particular way which I just followed from the tutorial video havent worked.
As you noticed I am a new to nodejs web development so if you could suggest websites or youtube channels to get me start it I would appreciate it.
It seems that it is not a db connection problem. Route matching http://localhost:3666/api/genres is not found in your application. Replace api/genres with /api/genres and I guess everything will work properly
I'm getting an error for trying to include a mongoose model written in a separate file.
throw new mongoose.Error.MissingSchemaError(name);
MissingSchemaError: Schema hasn't been registered for model "Cart".
Use mongoose.model(name, schema)
Within my server.js file my mongo models are defined before I call my routes. Which I've looked around and found defining your models after the routes are the cause of this error but that's not my case.
//Require db config
require('./app_api/config/model.js');
//Require routes config
var routesAPI = require('./app_api/config/routes.js')
var app = express();
Within my model.js file I require my separate schemas.
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/followdata';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
console.log('Mongoose disconnected');
});
// SCHEMA DECLERATION
require('../models/user');
require('../models/userCart');
So I'm not really sure what the problem is.
This is how I try to bring in my cart model into my user model schema.
var mongoose = require( 'mongoose' );
var jwt = require('jsonwebtoken');
var crypto = require('crypto');
var Cart = mongoose.model('Cart');
var Schema = mongoose.Schema;
var userSchema = new Schema({ ......... });
And within my userCart.js file I export it properly.
module.exports = mongoose.model('Cart', cartSchema);
You need to require in your Cart schema if you want to use it in your User model schema.
So, you would need var Cart = require('yourPathToCart/cart') instead of var Cart = mongoose.model('Cart') (the previous line of code is attempting to create a new model named Cart and this is where your error is coming from) in your User model schema file.
I am new to mongoDB and I'm currently working on setting it up with Node express server. I wonder how to manage concurrent requests to the mongodb to read the collection data using the mongoose driver module.
For example:
If 100 users are accessing my server at a time (http://xxxxxx.com/showusers), how will the mongodb connection in the express server work? Will it be a single connection or split into 100 connections, one for each request?
How can I close the connection object in mongodb efficiently after the operation? Or can we leave the connection in the express server as in the below code?
Here follows my code..
Server.js
var express = require('express');
var app = express();
app.set('port', config.port);
app.get('/users',storeusersapi.showUsers);
app.get('/storeUser',storeusersapi._insertUserDetails);
app.get('/findUser/:email',storeusersapi._findUser);
app.listen(app.get('port'),function(){
log.info('Express app started on port ' + app.get('port'));
});
storeusersapi.js
var mongoose = require('mongoose');
var log = require('../config/logger');
// Mongoose connection to MongoDB (ted/ted is readonly)
mongoose.connect('mongodb://localhost/mydb', function (error) {
if (error) {
log.error("MongoDB Connection failure - " +error);
}else{
log.info('MongoDB is connected Successfully!!!');
}
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: String
});
// Mongoose Model definition
var User = mongoose.model('users', UserSchema);
exports.showUsers = function(req,res){
User.find({}, function (err, docs) {
res.json(docs);
});
};
exports._insertUserDetails = function(req,res){
var object = new User({first_name:'bob',last_name:'sel',email:'sel#xxxxx.com'});
object.save(function (err) {
if (err) {
log.error('Insertion error - '+ err);
}
else {
log.info("User Stored into database!!!");
}
});
};
exports._findUser = function(req,res){
User.find({ email: req.params.email }, function (err, docs) {
res.json(docs);
});
};
I have answered for both of your question separately.
1. How will the mongodb connection in the express server work?
Once a connection is created to the mongodb database.(using mongoose or any other framework) It will create a pool of connections with that. (Mongoose default pool size is 5, 100 in python) The created connection pool is maintained by the driver therefore those connections can be re-used when connections to the database are required.
The best practice is to create a new connection only once for the whole application. Once connection is created the connection object will be used as a singleton. When you connect to the database using mongoose models, separate connections are allocated from the created connection pool.
If you are going to create a new connection each time then It will cause to a connection churn.
2. How can I close the connection object in mongodb efficiently after the operation ?
I am not sure 100% about this answer. My suggestion is to disconnect the connection when the express application exits.
var db = mongoose.connect('mongodb://localhost:27017/database');
db.disconnect();
According to my knowledge what you have don in the code is correct. You have created a new connection only once. Since the connection pool is created with that you don't need to create more connections.
Please go through this link to get a clear understanding on connection pools and their usage.
https://dzone.com/articles/deep-dive-connection-pooling
I'm using Express.js and MongoLab and I followed the Heroku setup to get MongoDB working in production throwing this code in my app.js.
//Mongo on Heroku Setup
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('mydocs', function(er, collection) {
collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
});
});
});
and I have the following routes and field for my email form (also in app.js):
//Routes
app.get('/', function(req, res) {
res.render('index', {
title: 'DumbyApp'
});
});
//save new email
app.post('/', function(req, res){
emailProvider.save({
address: req.param('address')
}, function( error, docs) {
res.redirect('/')
});
});
This renders the new form on the index page and lets me save it locally but not in production because I don't know how to setup my email collection. Can anyone walk me through this? brand new to using MongoDB and Node.js, so could use some help.
EDIT:
In The MongoLab Database Interface, I made a collection called emails. Is this the right course of action?
EDIT 2:
Here's defining EmailProvider in app.js along with the file itself.
app.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, EmailProvider = require('./emailprovider').EmailProvider;
var emailProvider= new EmailProvider('localhost', 27017);
emailprovider.js
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmailProvider = function(host, port) {
this.db= new Db('localdb', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
EmailProvider.prototype.getCollection= function(callback) {
this.db.collection('emails', function(error, email_collection) {
if( error ) callback(error);
else callback(null, email_collection);
});
};
//save new email
EmailProvider.prototype.save = function(emails, callback) {
this.getCollection(function(error, email_collection) {
if( error ) callback(error)
else {
if( typeof(emails.address)=="undefined")
emails = [emails];
for( var i =0;i< emails.address;i++ ) {
email = emails[i];
email.created_at = new Date();
}
email_collection.insert(emails, function() {
callback(null, emails);
});
}
});
};
exports.EmailProvider = EmailProvider;
While the connection code in the first code box appears to be correct, the emailProvider object isn't using it. Instead, in app.js, the EmailProvider is being connected to localhost:27017 and the database name is hardcoded in emailprovider.js as 'localdb'.
What you want to do instead is use the connection information provided in the MONGOLAB_URI environment variable in your EmailProvider, which contains the host, port, and database name already.
There are a number of ways to go about doing this, but one way would be to move your connection code from that first code box into the EmailProvider constructor, and then change the constructor so that it takes a URI instead of a host and port. That way, you can pass the MONGOLAB_URI variable to the constructor in app.js.