insert user data into mongodb database - javascript

I am trying to insert data into a mongodb database.
I am able to submit user data and display it with...
app.get('/process_get', function (req, res) {
response = {
first_name:req.query.firstName,
last_name:req.query.lastName,
username:req.query.userName,
password:req.query.password,
email:req.query.email
};
console.log(response);
res.end(JSON.stringify(response));
})
I then opened a connection with mongodb and created a "test" collection successfully...
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
if(!err) { console.log("MongoDB server is connected!") }
var collection = db.collection('test');
})
I tried "collection.insert({name:req.query.firstName});"
but this obviously didn't work because no "req". How do I make the inputs global
so I can simply insert them?

You don't have to do this within the database connection callback. Simply connect to your database in the process and then invoke the models.
//Setup Server and connect to mongoDB
var app = require('express')();
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/exampleDb');
//Create the model
var testSchema = mongoose.Schema({
..
});
var Test = mongoose.model('test', testSchema);
//Now use the model to save the object in the route controller
app.get('/process_get', function (req, res) {
response = {
.. //build the object based on some input or pas req.body directly
};
console.log(response);
new Test(response).save().then(function(result) {
res.end(JSON.stringify(result));
});
});
NB! You should split this logic out in different files to keep your project easier to maintain. The only reason for me to have it all in one file is to remove complexity.

Related

How to create a loop for SELECT function, to keep data updated?

I'm using an Oracle database, and every time it updates, the server doesn't understand this update and needs me to drop it for it to update the data.
const express = require('express');
const oracledb = require('oracledb');
const app = express();
var cors = require('cors')
app.use (cors())
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// Connection details for the Oracle database
const connectionString = 'dbprod';
const user = 'sapiensproducao';
const password = 'fabrica';
// Connect to the database
oracledb.getConnection(
{
connectionString: connectionString,
user: user,
password: password
},
function(err, connection) {
if (err) {
console.error(err.message);
return;
}
console.log('Connection was successful!');
// Execute a SQL query
const query = 'SELECT CODEMP,CODORI,NUMORP,SEQEOQ,DATREA,HORREA,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OBSEOQ from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
connection.execute(query, [], (err, result) => {
if (err) {
console.error(err.message);
return;
}
console.log('Query was successful!');
console.log()
// Render the HTML template and pass the query results as a local variable
app.get('/teste', (req, res) => {
res.json(result.rows)
});
});
}
);
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
I thought of creating a loop for this SELECT function, but how can I create it?
How can I keep running this select in a loop, to keep the data always updated?
In the structure of your web server, you only ever query the database once and then create an endpoint to serve that data. Instead, create an endpoint which queries the data whenever it's invoked. Which may look more like this:
// define the endpoint
app.get('/teste', (req, res) => {
// within the endpoint, query the database
oracledb.getConnection(
{
connectionString: connectionString,
user: user,
password: password
},
function(err, connection) {
if (err) {
console.error(err.message);
// DON'T DO THIS, return an actual response to the user
return;
}
console.log('Connection was successful!');
const query = 'SELECT CODEMP,CODORI,NUMORP,SEQEOQ,DATREA,HORREA,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OBSEOQ from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
connection.execute(query, [], (err, result) => {
if (err) {
console.error(err.message);
// DON'T DO THIS, return an actual response to the user
return;
}
console.log('Query was successful!');
console.log();
// return the results to the user
res.json(result.rows);
});
});
});
The key difference here is that instead of wrapping the endpoint in the query, you wrap the query in the endpoint. So every time the endpoint is invoked it re-queries the database.
Please also note the comments for your error handling. If you just return; from the function and never return a response to the client, the client will just hang until it times out. Return an actual response, which can include error codes, messages, anything you like. Even just res.json(false); would be better than no response at all.

Using a variable as a query in axios

I'm attempting to use a variable userEmail (which is assigned the user's email who is currently logged into my app) as a query for my api as I only want to search and return documents from my mongodb that relate to that specific email. I'm struggling to figure out how to pass this variable from my reactjs app to my api and utilising it, I don't even know if it is possible so any help would be great.
I'm using axios to make my GET request.
api.js contains my api helper functions
export async function surveyApiGet () {
let response = await axios.get('http://localhost:6000/'); // dateApi.js
return response.data;
}
dateApi.js is the api surveyApiGet() calls and at the moment my query is just regex that matches any emails, rahter than filtering to just the current user.
let MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', function (req, res) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("manderleydb");
var query = { userId : /^(.)/ };
dbo.collection("manderleySurveyCompleted").find(query).sort({ date: 1}).limit(1)
.toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
res.status(200).json(JSON.stringify(result));
});
});
});
app.listen(6000, () => {
console.log('listening on port 6000');
});
Landing.js is where I make the call to my api helper function
surveyApiGet()
.then(response => {
// code
})
.catch(err => {
err.message;
});
For this, you can do a POST request to your Nodejs API and you can include the user's email with that request. To do so what you have to do is something like the following.
const usersEmail = "example#email.com"
Then through Axios, you can post this code to Nodejs API as follows.
const data = await axios.post("http://localhost:6000/", {
usersEmail : usersEmail
});
After you send this to Nodejs you can hold the value of the user's email through the request's body as follows. Change your endpoint to post instead of get.
app.post("/", function (req, res) {
const userEmail = req.body.userEmail;
//Put your MongoDB query and the status code here.
})
Drop a comment if you have any unclear points.

How to update record using id in nodejs

I am new in Node Js and trying to learn it. I am currently follow this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ but its incomplete.
I want, if I click on any user from the list of users, it will take me to new page and show the record in form for update. I don't know how to send data onclick, find the record from the db and show it inside a form to update.
Here is the index file with all the functions:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*Get Hello world page*/
router.get('/helloword', function(req, res){
res.render("Helloworld", {title:'Hello, World!'});
});
/*Get UserList*/
router.get('/userlist', function(req, res){
var db = req.db;
var collection =db.get('usercollection');
collection.find({}, {}, function(e, docs){
res.render('userlist',{
"userlist": docs
});
});
});
/*Get New User Page*/
router.get('/newuser', function(req, res){
res.render('newuser',{title: 'Add New User'})
});
/* POST to Add User Service */
router.post('/adduser', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : userName,
"email" : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
res.redirect("userlist");
}
});
});
module.exports = router;
Thanks in advance please help me for guidance
It looks like you want to use findAndModify (docs)
Using your code you could implement an update route like so.
router.post('/user/:userId', function (req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
collection.findAndModify(
{_id: req.query.userId}, // query
[['_id', 'asc']], // sort order
{
$set: {
"username": userName,
"email": userEmail
}
}, // replacement
{}, // options
function (err, object) {
if (err) {
console.warn(err.message); // returns error if no matching object found
} else {
console.dir(object);
}
});
});
However this does not have any validation to make sure that the user has the correct permissions to update this, make sure you add something like the query
{$and: [{_id: req.query.userId}, {createdBy: req.user}]}

MongoDB and Express: Type Error: Converting Circular structure to JSON

I am new to MEAN stack. I am trying to retreive a list of documents from MongoDB. I have used Visual Studio 2013 community edition to create a basic Nodejs Express application. Visual studio created app.js file on the root for configuration. I have put following code in app.js which is relevant to mongodb:
var mongo = require('myDB');
var db = new mongo.Db("myDB", new mongo.Server("localhost", "27017"),
{ safe: true }, { auto_reconnect: true });
// Make our db accessible to our router
app.use(function (req, res, next) {
req.db = db;
next();
});
In the routes folder that visual studio created, I have created a js file which will perform CRUD operations. I have following code in this file:
var express = require('express');
var router = express.Router();
router.get('/myRecords', function (req, res) {
var db = req.db;
db.open(function (err, db) {
if (err)
console.log(err);
else {
var collection = db.collection('myCollection');
var dataToSend = collection.find();
res.send(dataToSend);
}
})
});
module.exports = router;
I am Type Error: Converting Circular structure to JSON.
I am trying to not using any schema.
Please advice.
For those of you, who encounter the similar problem, find() doesn't return the document, we need to use toArray to retrieve documents. Following code did the trick:
router.get('/myRecords', function (req, res) {
var db = req.db;
db.open(function (err, db) { // <------everything wrapped inside this function
db.collection('myCollection', function (err, collection) {
collection.find().toArray(function (err, items) {
res.send(items);
db.close();
});
});
});
});

Parsing nested JSON using body-parser and express

I have an iOS app which is sending a JSON packet to a webserver. The webserver code looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("MongoDB connection is open.");
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
X: Number,
Y: Number,
Orientation: Number,
UserID: String,
Time: String
});
// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);
// create application/json parser
var jsonParser = bodyParser.json();
// URL management
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
console.log(req.body);
}
});
// Start the server
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('App listening at %s:%s',host, port)
});
The key part is the app.post method which processes the incoming http request being sent from my iOS app. At the moment, the method which prints the req.body to the console looks like this:
{
datapoint_1:
{ timestamp: '2015-02-06T13:02:40:361Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 271.3345946652066 },
datapoint_2:
{ timestamp: '2015-02-06T13:02:40:961Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 273.6719055175781 }
}
So, you can see the request is a nested JSON object. Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose). However, I can't seem to figure out how to do much of anything with the req.body. I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema. Can anyone provide some guidance on how to insert these datapoints into the mongoose database?
Set body-parser's extended property to true to allow parsing nested objects.
var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
Answering my own question. But, after figuring out how to access the key/value pairs inside the nested JSON object... it became relatively easy to figure out the rest. The updated app.post function now looks like this:
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
for(var datapoint in req.body){
//create new instance of LocationCollection document
var point = new LocationsCollection({
X:Number(req.body[datapoint]["x"]),
Y:Number(req.body[datapoint]["y"]),
Orientation:Number(req.body[datapoint]["orientation"]),
Time:req.body[datapoint]["timestamp"],
UserID:req.body[datapoint]["id"]
});
//insert the newly constructed document into the database
point.save(function(err, point){
if(err) return console.error(err);
else console.dir(point);
});
}
}
});
I can test if this worked by putting the following method inside the callback function once the mongodb connection is first established:
//Find all location points and print to the console.
console.log("Searching for all documents in Location Points Collection");
LocationsCollection.find(function(err,data){
if(err) console.error(err);
else console.dir(data);
});
This will print any documents that have been previously added to the database. Hopefully this helps.
Try somthing like this.
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){
try {
JSON.parse(buf);
} catch(e) {
res.send({
error: 'BROKEN_JSON'
});
}
}}));
It should be a simple for (var key in obj) loop:
app.post('/update', jsonParser, function (req, res) {
var locationObject = req.body(),
insertObjects = [],
key;
for (key in locationObject) { // loop through each object and insert them into our array of object to insert.
insertObjects.push(locationObject[key]);
}
if (!insertObjects.length) { // if we don't have any object to insert we still return a 200, we just don't insert anything.
return res.status(200).send({
success: true,
message: 'Nothing inserted, 0 locations in POST body',
count: 0;
});
}
LocationsCollection.create(insertObjects, function (err, res) {
if (err) {
return res.status(400).send({
success: false,
message: err.message
});
}
// we have successfully inserted our objects. let's tell the client.
res.status(200).send({
success: true,
message: 'successfully inserted locations',
count: insertObjects.length;
});
});
});
Mongo allows for inserting multiple documents with a single callback, which makes this a lot easier.
This also checks the schema to ensure only proper documents are created.

Categories