How to insert mongodb data from another js file - node.js - - javascript

I have watched and read loads of tutorials now on node.js and mongodb. I know how to create databases, Insert data, show that data on a ejs file, etc etc. However, I have no idea how to insert data from that ejs file.
For example:
I have an app.js and a mongodb.js the app runs my server and the mongodb.js creates a database and inserts some data - not with mongoose but rather with mongodb. I also have a few ejs files that get the data from mongodb.js and displays it. Heres my mongodb.js:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
exports.drinks = [
{ name: 'Manu', rate: 3 },
{ name: 'Martin', rate: 5 },
{ name: 'Bob', rate: 10 }
];
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('users');
// Insert some users
collection.insert(exports.drinks, function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
console.log(collection.users.find());
//Close connection
db.close();
});
}
});
Then in my app.js I have this:
//index page
app.get('/', function(req, res) {
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
And on my ejs:
<ul>
<% drinks.forEach(function(drink) { %>
<li><%= drink.name %> : <%= drink.rate %></li>
<% });; %>
</ul>
But now I want to be able to update/insert data into my database from my ejs (or even from my app.js).
For example if I have a form and I want the user to type their name inside I want that to be saved in my db. How do I do this?

Ejs only template engine (View in MVC), It cant update and insert database (Controller do this). You need make a route (POST) for get user data and update to database.

Related

Read SQLite database with Node.js

Having this SQLite DB I'm trying to read the data from it. So, from table Athlete I want to read the first 3 columns.
This is the code (app.js):
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('ocs_athletes');
db.serialize(function () {
db.each('SELECT athlete_id, name, surname FROM Athlete', function (err, row) {
console.log('User: ', row.athlete_id, row.name, row.surname);
});
});
db.close();
The file app.js is in the same folder as the db file - ocs_athletes.
Running in cmd node app.js returns this error message:
/home/dd/Documents/Projects/OCSapp/app.js:6
console.log('User: ', row.athlete_id, row.name, row.surname);
^
TypeError: Cannot read property 'athlete_id' of undefined
at /home/dd/Documents/Projects/OCSapp/app.js:6:31
at replacement (/home/dd/Documents/Projects/OCSapp/node_modules/sqlite3/lib/trace.js:25:27)
at Statement.errBack (/home/dd/Documents/Projects/OCSapp/node_modules/sqlite3/lib/sqlite3.js:14:21)
Why is this happening?
Try connecting to db like this.
let db = new sqlite3.Database('./ocs_athlete.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the my database.');
});
Give path of .db file. This will work.
There are three opening modes:
sqlite3.OPEN_READONLY: open the database for read-only.
sqlite3.OPEN_READWRITE : open the database for reading and writting.
sqlite3.OPEN_CREATE: open the database, if the database does not exist, create a new database.
To open the chinook sample database for read and write, you can do it as follows:
let db = new sqlite3.Database('./ocs_athlete.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the ocs_athlete database.');
});

mongo database doesn't show up in command line

I don't understand why my mongo db isn't showing up when I run "show databases" in the command line. I see other mongo db's I created in the past, but not the current one. Here is my code: (using mongoose ORM):
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fuelTracker');
var Schema = mongoose.Schema;
var fuelSchema = new Schema({
time : { type : Date, default: Date.now },
miles : Number,
gallons: Number
});
var FuelStop = mongoose.model('FuelStop', fuelSchema);
module.exports = FuelStop;
And where I'm attempting a basic model.save operation:
app.post('/', function (req, res ) {
results = req.body;
var fuelStop = new FuelStop (results)
fuelStop.save(function() {
console.log('record saved to monogoDB');
});
})
Any clue as to why my 'fuelTracker' database doesn't appear in the command line when I run 'show databases' within mongo?
THANK YOU!!
did you try show dbs? show databases print all databases available, see the doc here: https://docs.mongodb.com/manual/reference/mongo-shell/
The database doesn't get created until you insert data into a collection in the database.
I tested your code by creating and running a script to seed the fuelTracker database with example JSON data. I then ran show databases and was able to see fuelTracker listed.
If you would like to try this, in a new file seed.js:
const db = require('./fileName.js');
const fs = require('fs');
let fuelData = fs.readFileSync('./data.json', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
let jsonFuel = JSON.parse(fuelData);
db.remove({}, () => {
console.log('Successfully removed fuel data');
db.collection.insert(jsonFuel, (err, docs) => {
if (err) {
console.log(`error inserting data: ${err}`);
} else {
console.log(`Fuel data was stored: ${docs}`);
}
});
});
Then create example data in data.json:
[
{
"time":"04/18/2018",
"miles":"28",
"gallons":"30"
}
]
Then run your seed file and your database should hopefully be showing up.

MongoDB&NodeJS: How to display a certain field on a Jade file on a server

So I just started learning MEAN and I want to show only a certain field of a database I've made to a Node server. I'm using Express as well. Here is my code so far.
index.js
router.get('/generate', function(req, res) {
// get out mongoclient to work with our mongo server
var MongoClient = mongodb.MongoClient;
// where the mongodb server is
var url = 'mongodb://localhost:27017/data';
MongoClient.connect(url, function(err, db) {
if(err) {
console.log('Unable to connect to server', err);
} else {
console.log('Connection established');
var collection = db.collection('compliments');
collection.find({}).toArray(function(err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.json(result); // problem here
} else {
res.send('No documents found');
}
db.close();
});
}
});
});
generate.jade
doctype html
html
head
title("Compliment Generator")
body
h1 !{title}
block content
h3.
!{compliment}
This is what it looks like on localhost:3000/generate
[{"_id":"570b50f8265f2536d2fd6ed6","type":"compliment","content":"You are absolutely gorgeous."},{"_id":"570b50f8265f2536d2fd6ed7","type":"compliment","content":"You are wonderful."},{"_id":"570b50f8265f2536d2fd6ed8","type":"compliment","content":"I could look at you all day."}]
How do I make it so that it only displays the "content"? Thanks!
If I understand correctly you only want the content to be returned from the query.
The below link should be of use:
https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/
You essentially want to modify the query to only retrieve the "Content" part like so:
collection.find({}, { content: 1, _id:0 })
This will specify that you don't want to include the "_id" (which is included by default) and you do want to include the "content".

Fetching data from mongodb through nodejs and express to a html page

Basically, I want to show particular fields from "employees" collection into a html page. But even after searching a lot on web, I'm unable to do so.
Here is the route part from the server.js file:
app.get('/fetching', function(req, res){
connection.fetcher(function(data)
{
res.render("testing.html",data);
}
);
});
Now this is the part from connection.js file:
var fetcher= function(callback) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('employees');
collection.find({},function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
callback(result);
}
});
}
});
Now, findOne is working fine and returning the value to server.js file perfectly. But I need to use "find", so how to send the complete array to the server.js through callback?
And moreover, I need to send that retrieved data from server.js to a HTML file called testing.html through rendering and display it through angular js. Please explain a simple way to do so.
EDIT:
I got to know how to work with "find", I just used "toArray" alongwith "find" in function. And now, I'm able to return the value to server.js through call back. But the other question is still unsolved: How do I pass those values to the html page?
Using ejs, you need to set the view engine:
app.set('view engine', 'ejs');
Then get your data:
app.get('/employees',(req , res) =>{
db.collection('employees').find().toArray(function(err , i){
if (err) return console.log(err)
res.render('index.ejs',{employees: i})
})
});
The .ejs file would be like this:
employees
<ul class="employees">
<% for(var i=0; i<employees.length; i++) {%>
<li class="employees">
<span><%= " Nome: " +employees[i].name+"."%></span>
<span><%=" Address: " + employees[i].address%></span>
</li>
<% } %>
</ul>
Just a simple way using ejs. Hope it helps to clarify things.

Node.js app giving ERR_EMPTY_RESPONSE

I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});
updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong

Categories