Inserting in mongodb with nodejs - node.js

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

Related

How do I get data from a MongoDB collections using node.js and render it as a JSON in expess

I'm trying to get data from a collections database in my MongoDB using Node, which I've done successfully. My only problem is how to render the obtained data from the collections and posting it into the express app.
const { MongoClient } = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close()
})
})
}
main().catch(console.error)
I solved my own problem by just performing an app.get() in the part were it says Mongoclient.connect() and the rest is done by logic, it displays now in the express and in postman as well.
const {MongoClient} = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
app.get("/", (req, res) => {res.json(result)})
db.close()
})
})
app.listen(4000, function() {
console.log("listening to port 4000)
}
main().catch(console.error)
Here is another way:
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const app = express();
const url = 'mongodb://localhost:27017';
const dbName = 'test';
const port = 3000;
app.listen(port);
// Type this in your browser to see db data: http://localhost:3000/
app.get('/', function(req, res) {
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(function(err) {
console.log("Connected to server.");
const db = client.db(dbName);
db.collection("books")
.find({})
.toArray(function(err, result) {
if (err) throw err;
client.close();
console.log("Done reading db.");
res.send(JSON.stringify(result));
});
});
});

how to redirect to another page from a node.js server

i have been struggling for the pas few days i want to redirect to another page from my node.js server.
first by website is redirecting me to my server to do a task but when that task is done i want the server to redirect me back to my website.
here is the node js server code.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
var urlQuery = url.parse(req.url, true).query;
removeItem(urlQuery.itemToRemove);
addItem(urlQuery.itemToAdd);
**// i have been trying to redirect to my html site **
**// i have got a error saying TypeError: res.redirect is not a function**
res.redirect('index.html');
res.end();
}).listen(8080);
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = {
itemName: remove
};
dbo.collection("shoppingCart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
console.log("deleted:" + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = {
itemName: create
};
dbo.collection("shoppingCart").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("document inserted:" + myobj);
db.close();
});
});
}
}
You are getting that error because response.redirect() is an express function and your app is based purely on nodejs http library.
You can accomplish what you have mentioned this way:
res.writeHead(301,{Location: 'your-location'});
res.end();
You are not creating the server properly. Try to keep your code clean,Write separate API for serving index.html, not inside creating the server.
TypeError: res.redirect is not a function
This is because res.redirect is an express function and you're using plain http node server.
You can consider using express for handling redirects for you.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = 'mongodb://localhost:27017/';
// express
const express = require('express');
const app = express();
const port = 8080;
// for templating
// create `views/` folder
// and place `index.pug` and `redirected-page.pug`
app.set('view engine', 'pug');
app.get('/redirect', (req, res) => {
res.render('redirected-page');
});
app.get('/', (req, res) => {
var urlQuery = url.parse(req.url, true).query;
Promise.all([
removeItem(urlQuery.itemToRemove),
addItem(urlQuery.itemToAdd),
]).then(() => {
res.redirect('redirect');
});
});
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myquery = {
itemName: remove,
};
dbo.collection('shoppingCart').deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log('deleted:' + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myobj = {
itemName: create,
};
dbo.collection('shoppingCart').insertOne(myobj, function(err, res) {
if (err) throw err;
console.log('document inserted:' + myobj);
db.close();
});
});
}
}
app.listen(port, () => console.log(`Server is running at ${port}!`));

NODE.js Insert into SQL Server

I am trying to perform an INSERT into my SQL Server through my NODE.js server
but it is not working.
I believe it is not a connection problem because (as I will demonstrate at the end of the post) I did a select that worked, so I must be making some mistake in the node.js code.
This is the first javascript system I create.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
var body = req.body;
var sql = require("mssql");
console.log("C1");
sql.connect('mssql://login:pswd#serv/db', function (err) {
if (err) console.log(err);
// create Request object
console.log("Connected!");
var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"
// query to the database and get the records
sql.query(insert, function (err, result) {
if (err) console.log(err)
// send records as a response
console.log("1 record inserted");
});
});
});
//var server = app.listen(5000, function () {
// console.log('Server is running..');
//});
What am I doing wrong? Because the INSERT did not even show my console.logs =/
When I performed a test doing a select it worked, so
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = {
user: 'papercut',
password: 'Portage.2018',
server: 'devsqlcl2:1433',
database: 'AgrM6',
port: "1433",
dialect:",ssql",
dialectOptiond:"SQLEXPRESS"
};*/
// connect to your database
sql.connect('mssql://login:pswd#server:1433/database', function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
This SELECT statement worked.

Can't import module with require() in nodejs

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

How to make MongoDB available inside Express' HTTP methods?

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

Resources