var express = require('express');
var routes = require('./routes');
var socket = require('socket.io');
var fs = require('fs');
var app = module.exports = express.createServer();
var Server = require('mongodb').Server,
Db = require('mongodb').Db,
Connection = require('mongodb').Connection;
var host = 'localhost';
var port = Connection.DEFAULT_PORT;
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:false});
db.open(function(err, db) {
console.log('opened');
app.listen(3000);
});
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
var array = collection.findOne({word:'TEST'}, function(err, item) {});
console.log(array);// <----always "undefined"
});
});
I try to insert the object into the database. And by using "console.log(array)" everytime,I find that it always be "undefined". Is it can't be insert into the database or can't be found from the database. How can I solve it??
But, The 'console.log(item)' shows 'null'. So does it sucessfully insert into the database, or should I change another way to get the object from database.
collection.findOne is asynchronous, so you don't use the return value of the function; instead, you should console.log(item) from inside your (currently empty) callback.
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
collection.findOne({word:'TEST'}, function(err, item) {
console.log(item);
});
});
});
Related
I'm developing a nodejs webapp and I have a problem.
I have a twitter.js module that expose some functions to use in other files.
My main application, app.js, import it correctly and can use the functions.
The problem is, if I import it in another .js file (via the var twitter = require(./twitter) method), it doesn't load, I can see that via console.log(twitter) and also because it doesn't recognize the functions.
This happens if app.js requires it. I copied the twitter.js file and name it differently, and if I import that it works.
How can I solve this problem?
Thanks
EDIT: Adding some code
This is the main app, app.js
var express = require("express");
var bodyParser = require("body-parser");
var path = require("path");
var twitter = require("./twitter");
var mongo = require("./mongo");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}))
app.use(express.static(path.join(__dirname,'public')));
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.get("/",function(req,res){
res.render("index.ejs")
});
app.get("/twitter",function(req,res){
twitter.getTrends(res);
});
app.post("/sendMessage",function(req,res){
twitter.postTwit(req.body.valore);
});
app.get("/pullData",function(req,res){
mongo.pullData(res);
});
app.listen(8080, function(){
console.log("server started on 8080");
});
Next is the twitter.js file:
var Twitter = require('twitter'); //import package
var mongo = require("./mongo");
var T = new Twitter({ ---developer keys here --})
exports.getTrends = function(res){
var params = { id: 23424853, count: 10}
T.get('trends/place',params,gotData);
function gotData(err,data,response){
res.render('tweets',{ data: data[0], length: 10});}
}
exports.postTwit = function(value){
T.post('statuses/update', {status:value}, function(error, tweet, response) {
mongo.pushdata(tweet.id_str);
});
}
exports.loadTwit = function(res,value){
var params = {id: value}
T.get('statuses/show/', params, function (err, data, response) {
console.log(data);
res.render('db',{ data: data});
});
}
and finally the mongo.js file, for the mongo database
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
var twitter = require('./twitter');
exports.pushdata = function(value){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var myobj = {id: value};
db.collection("tweets").insertOne(myobj, function(err, res) {
if (err) throw err;
db.close();
});
});
}
exports.pullData = function(res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("tweets").find({}).toArray(function(err, result) {
result.forEach(function(entry) {
twitter.loadTwit(res,entry);
});
db.close();
});
});
}
all these files are in the same folder.
You have created circular dependency between mongo.js & twitter.js.
mongo.js tries loading twitter.js which in turn requires mongo.js. Thats the problem. Remove this circular dependency.
Maybe you can pass the twitter object as a parameter when you call the functions of mongo.js. Or something else.
For e.g.
mongo.js
var twitter = require('./twitter');
// pass the twitter object as a parameter
exports.pullData = function(twitter, res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("tweets").find({}).toArray(function(err, result) {
result.forEach(function(entry) {
twitter.loadTwit(res,entry);
});
db.close();
});
});
}
I'm unable to export the db object for using in my routers (controller). Heres the file where i connect to the database and attempt to export db object:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
database = db;
module.exports = database;
});
and where i try using it in one of my routers:
var db = require('../path/to/file/above');
// Redirect to application
router.get('/', function(req, res, next) {
try {
db.close();
} catch (err) {
console.log(err);
}
res.render('index',{});
});
"console.log(err)" says "db.close() is not a function".
Q: How do i properly export the db object so i can use it in my routers?
i think there is some problem with your module.exports try this
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(db);
});
}
module.exports = connectMongo;
You can use mongoskin to access the mongodb and can export the db object.
e.g.
var mongo = require('mongoskin');
var url = 'mongodb://localhost:27017/database';
var db = mongo.db(url, {native_parser:true});
module.exports = db;
And, in your router,
var db = require('../path/to/file/above');
// Redirect to application
router.get('/', function(req, res, next) {
try {
//some db operations
} catch (err) {
console.log(err);
}
res.render('index',{});
});
Other solution is to pass the callback as suggested by #Asif.
This is what my database file (database.js) ended up to be:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var express = require('express');
var app = express();
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
database = db;
});
// Returns DB object when called
module.exports.get = function() {
return database;
}
and using it like this (note that you have to call the get function in a router.get() for example, calling it directly won't work since the connection won't be open yet):
var database = require('./database.js');
var assert = require('assert');
var express = require('express');
var router = express.Router();
// Redirect to application
router.get('/', function(req, res, next) {
var db = database.get();
// Mongo Query here
res.render('index',{});
});
I'm trying to use MongoDB with Node/Express. I made the official example work:
var express = require('express')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var app = express()
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
insertDocuments(db, function() {
db.close()
})
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
// Some code
], function(err, result) {
// Some code
callback(result)
})
}
app.get('/insert-document', function(req, res) {
// res.send()
})
How can I make it so that Mongo is available inside Express' HTTP methods? For instance, to use insertDocuments() inside app.get('/insert-document', function(req, res)?
EDIT (full server.js file):
var express = require('express')
// var PouchDB = require('pouchdb')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')
var app = express()
var compiler = webpack(config)
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
var db
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null)
assert.equal(3, result.result.n)
assert.equal(3, result.ops.length)
console.log("Inserted 3 documents into the document collection")
callback(result)
})
}
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
stats: {
colors: true,
chunks: false
}
}))
// enable hot-reload and state-preserving
// compilation error display
app.use(require('webpack-hot-middleware')(compiler))
app.get('/docs', function(req, res) {
// res.send()
insertDocuments(db, function() {
db.close()
})
})
app.listen(8080, 'localhost', function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:8080')
})
I get
TypeError: Cannot read property 'collection' of undefined
at insertDocuments (/home/alex/node/project-mongo/build/dev-server.js:24:22)
Refer codes here, save the connection db as one global variable, sample codes as below.
var db;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get('/insert-document', function(req, res) {
// insertDocuments() could invoked here.
});
I have a nodejs app which connects to Mongodb installed locally with the code :
var mongo = require('mongodb');
var nodemailer = require("nodemailer");
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('clients', server, {safe:false});
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'clients' database");
db.collection('clients', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'clients' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findAll = function(req, res) {
db.collection('clients', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Now I want to move this code to Heroku. According to Heroku, my code should look something like :
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) {
});
});
});
I can't seem to figure out how to restructure my code for it to work on Heroku.
Does it have to be on heroku?
You could keep your code on Heroku, easily configure a free Mongodb instance/datasource in Mongolab ( https://mongolab.com/products/pricing/ ) and adjust your code to connect to the free Mongodb instance on Mongolab:
mongodb://dbuser:dbpassword#dfs12345.mongolab.com:56789/dbname
Ref: http://docs.mongolab.com/connecting/
I'm trying to insert some data in my mongodb with nodejs whenever a socket is emitted. Here is the code:
io.sockets.on( "connection",function( socket ){
socket.on( "send", function( data ) {
console.log(data.name + " and the content is: " + data.content);
mongodb.connect( "mongodb://127.0.0.1", function( err, db ) {
if(err) throw err;
var to_be_inserted = {name: data.name,content: data.content};
db.collection("chat").insert(to_be_inserted,function(err,objects){
if(err) throw err;
});
})
})
})
However whenever I go to my mongo console and type
db.chat.find()
I cannot find the inserted record. I'm sure that I have mongod open and I'm sure that the socket is emitted. Moreover the consoloe.log before the insertion does work.
Here is my mongo client
var mongodb = require("mongodb").MongoClient;
My console which runs the nodejs server does not log any error.
You should specify a database name (here: myDatabase ) and a port number (for safety).
mongodb.connect("mongodb://127.0.0.1:27017/myDatabase", function( err, db ) {
When searching the record in the mongo shell try:
use myDatabase
db.chat.find()
You forget to include the port number and database of mongodb,
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
}
try this code
var MongoClient=require('mongodb').MongoClient;
var Server=require('mongodb').Server;
var mongoc=new MongoClient(new Server("localhost",27017));
mongoc.open(function(err)
{
db.collection(<collection_name>).insert(<query>,function(err,result)
{
});
const http = require('http');
const hostname = '127.0.0.1';
const port = 8081;
var express = require("express");
var bodyParser = require('body-parser');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
app.use(bodyParser.json());
app.get('/get', function (req, res) {
res.send('Hello World')
})
var data = {
title: 'my title',
content: 'my content'
};
// This responds a POST request for the homepage
app.post('/say/:userid', function (req, res) {
var queryParameter=JSON.stringify(req.query);
res.send('Hello POST'+req.params.userid+""+queryParameter);
})
app.post('/insert', function (req, res) {
console.log(req.body);
res.send('Hello POST'+JSON.stringify(req.body));
/* var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017"; */
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbase = db.db("mydb");
var myobj = { name: JSON.stringify(req.body.name), address:JSON.stringify(req.body.address) };
dbase.collection("student").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");