I am trying since 3 hours to store the data from html form to mongodb using noddejs.
while clicking on submit it shows another page which returns the data which has been submitted in json format but it is not being stored in database.
This is my app.js:
app.use(serveStatic(__dirname+"/index.html")).listen(8080);
var mongoUri = 'mongodb://localhost/test';
//Note that I am changing the dbname and trying to store data in different //db will also shows the same error
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database at ' + mongoUri);
});
console.log("connection successfull");
app.use(express.bodyParser());
app.use(express.static(__dirname + "/" ));
app.use(bodyParser.urlencoded({extended:true}));
app.post('/InquiryDetails', function(req,res){
res.json(req.body);
console.log(req.body);
});
require('./models/InquiryDetails');
app.listen(4000);
console.log('Listening on port 4000...');
this is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myskyllSchema = new Schema({
name: String,
email: String,
state: String,
country: String,
school: String,
profession: String,
phone: Number
});
mongoose.model('InquiryDetails', myskyllSchema);
This is my controller:
var mongoose = require('mongoose'),
InquiryDetails = mongoose.model('InquiryDetails');
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
Any help will be appreciated.
Just replace the code in app.js :
app.post('/InquiryDetails', function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
res.send(req.body);
});
});
instead of :
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
The reason is controller was unable to load and method add is not registered with post method. Now it is working.
Related
I want to preface this by saying I have read several posts here regarding this issue.
I have a node/express/mongo app with the following:
app.js:
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var morgan = require('morgan')
var mongoose = require('mongoose')
var passport = require('passport')
var app = express()
// MongoDB Setup
var configDB = require('./config/database.js')
mongoose.connect(configDB.url)
app.use(morgan('combined'))
app.use(bodyParser.json())
// Check security with this
app.use(cors())
// load our routes and pass in our app and fully configured passport
require('./routes')(app)
app.listen(process.env.PORT || 8081)
console.log('We are up and running, captain.')
routes.js
const AuthenticationController = require('./controllers/AuthenticationController')
module.exports = (app) => {
app.post('/register', AuthenticationController.register)
}
My mongo schema file Account.js:
const mongoose = require('mongoose')
const bcrypt = require('bcrypt-nodejs')
const Schema = mongoose.Schema
var accountSchema = new Schema({
email: String,
password: String,
likesPerDay: { type: Number, min: 0, max: 250 },
followPerDay: { type: Number, min: 0, max: 250 },
unfollowPerDay: { type: Number, min: 0, max: 250 },
commentsPerDay: { type: Number, min: 0, max: 250 },
comment: String,
hashtags: [String]
})
// methods ======================
// generating a hash. We hash password within user model, before it saves to DB.
accountSchema.methods.generateHash = function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
}
// checking if password is valid
accountSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.local.password)
}
// create the model for users and expose it to our app
module.exports = mongoose.model('Account', accountSchema)
And finally my controller file AuthenticationController.js
const Account = require('../models/Account.js')
// var bodyParser = require('body-parser')
module.exports = {
register (req, res) {
Account.findOne({email: req.body.id}, function (err, account) {
if (err) {
console.log('Could not regster user')
throw err
}
if (account) {
console.log('account already exists')
} else {
Account.insertOne({email: req.body.email, password: req.body.password}, function (err, res) {
if (err) {
console.log('could not insert')
throw err
}
console.log('inserted account')
Account.close()
})
}
})
}
}
I am getting an error in my AuthenticationController file when I call Account.insertOne function.
I get the error that
TypeError: Account.insertOne is not a function
Now several of the posts here on stack have advised that I make sure that I am exporting the model from my model class, which I am doing, and that would fix this issue. Its weird because the findOne method seems to be fine, but when I call the insertOne i get an issue.
Am I missing something here?
A Mongoose model doesn't have an insertOne method. Use the create method instead:
Account.create({email: req.body.email, password: req.body.password}, function (err, doc) {
The Mongoose docs show how to create documents:
Either via Account.create():
Account.create({email: req.body.email, password: req.body.password}, function (err, res) {
// ...
})
Or by instantiating and save()ing the account:
new Account({email: req.body.email, password: req.body.password}).save(function (err, res) {
// ...
})
edit
as of mongoose documentation, try using
Account.create({ ...params ... }, function (err, small) {
if (err) return handleError(err);
// saved!
})
insertOne command is not available in mongoose directly as mentioned in Mongoose Documentation. If you want to use insertOne command then you need to use bulk command in order to send this command to MongoDB server. Something like below. I hope this works.
Account.bulkWrite([
{
insertOne: {
document: {email: req.body.email, password: req.body.password}
}
}
}]
I have a working auth on a local project, but am trying to deploy it with Heroku and Mlab. I can post new objects, but cannot get my Auth to work. I am not sure why. I am using the MEAN stack with Angular 1.6.
Github
Heroku Project
This is how I am currently posting new objects to the hosted database.
var VENDORS_COLLECTION = "vendors";
var USERS_COLLECTION = "users";
// Create a database variable outside of the database connection
callback to reuse the connection pool in your app.
var db;
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err,
database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
app.post("/vendors", function(req, res) {
var newVendor = req.body;
newVendor.createDate = new Date();
db.collection(VENDORS_COLLECTION).insertOne(newVendor, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new vendor.");
} else {
res.status(201).json(doc.ops[0]);
}
});
});
This is how my auth works locally:
app.post('/auth/signup', function (req, res) {
User.findOne({ email: req.body.email }, function (err, existingUser) {
if (existingUser) {
return res.status(409).send({ message: 'Email is already taken.' });
}
var user = new User({
displayName: req.body.displayName,
username: req.body.username,
email: req.body.email,
password: req.body.password
});
user.save(function (err, result) {
if (err) {
res.status(500).send({ message: err.message });
}
res.send({ token: auth.createJWT(result) });
});
});
});
Tried to refactor to look like this but no luck.
app.post('/auth/signup', function (req, res) {
db.collection(USERS_COLLECTION).findOne...
I have just made a simple program to display and insert data from a database(sql server 2008). My code does the display of data. I am unable to get data inserted. It shows no error in terminal or browser.
Here is my javascriptfile
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
var sql = require("mssql");
var config = {
user: 'pkp',
password: 'pkp',
server: 'PRAVEEN\\SQLEXPRESS',
database: 'myneww'
};
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log(req.query.first_name);
var res=request.query('insert into Mytab values(req.query.first_name ,req.query.last_name)');
});
});
app.get('/alldata', function (req, res) {
sql.connect(config, 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 Mytab', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Here is my html file
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
I am able to get the values displayed in the console, means values are passed and retrieved from the form. But still not inserted into the database.
I'm not good in javascript, but I guess the line below is incorrect:
var res=request.query('insert into Mytab values(req.query.first_name ,req.query.last_name)');
It should be something like this.
var res=request.query('insert into Mytab values(' + req.query.first_name + ',' + req.query.last_name +')');
If not, you've got an idea.
First, you were not passing values properly to query and, secondly, you are not waiting for the record to insert. Add the callback that I added.
app.get('/process_get', function (req, res) {
//some code
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log(req.query.first_name);
request.query('insert into Mytab values('+req.query.first_name+','+req.query.last_name+')', function(err, recordset) {
if (err) {
console.log(err);
return res.send('Error occured');
}
return res.send('Successfully inserted');
});
});
});
Update
Use transaction to commit changes.
app.get('/process_get', function (req, res) {
//some code
var sqlConn = new sql.Connection(config);
sqlConn.connect().then(function () {
var transaction = new sql.Transaction(sqlConn);
transaction.begin().then(function () {
var request = new sql.Request(transaction);
request.query('Insert into EmployeeInfo (firstName,secondName) values ('+req.query.first_name+','+req.query.last_name+')').then(function () {
transaction.commit().then(function (recordSet) {
console.log(recordSet);
sqlConn.close();
return res.send('Inserted successfully');
}).catch(function (err) {
console.log("Error in Transaction Commit " + err);
sqlConn.close();
return res.send('Error');
});
});
});
});
Forgive me, if there is any typo.
Like the title entails.
I'm trying to make an application that when i put in certain info, it creates a link using mongoose _id. and express's app.get what i don't get is that to be able to join that directory i have to reload the whole server, which for the users and my sake a i don't want to do.
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var router = express.Router();
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
name: {
type: String,
unique: false
}
});
var collectionOfData = mongoose.model("dataType", collectedData);
io.on("connection", function (socket) {
socket.on("name", function (e) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
name: e
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
});
app.get("/mix", function (req, res) {
collectionOfData.find(function (err, data) {
res.send(data);
});
});
collectionOfData.find(function (err, data) {
data.forEach(function (uniqueURL) {
app.get("/" + uniqueURL._id, function (req, res) {
res.send("<h1>Hello " + uniqueURL.ipAddress + "</h1><p>" + uniqueURL.name + "</p>");
});
});
});
http.listen(10203, function () {
console.log("Server is up");
});
So what i'm trying to do is make it so i don't have to reload the whole server, and i'm able to just join the created directory when it's done being loaded.
figured i should put a quick example:
localhost:10203/55c2b2f39e09aeed245f2996
is a link a user just created the long
55c2b2f39e09aeed245f2996
is the effect of the _id, but when the user try's to connect to that site it won't work until i reload the server and obviously i'd like to avoid that haha.
I have a index.html file, but all that has is a socket.emit that sends "name" to the server
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
app.get('/:uniqueURL', function(req, res){
var id = req.params.uniqueURL;
res.send("Your requested id : " + id);
})
Try to use this above.
You are creating fix get path inside collectionData.find. That is the problem. So each time you have to reload the server by restarting.
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.