I am trying to store the data written in jade to be stored in MongoDB using monk, but it is neither storing the data nor prompting any error
connecting to MongoDB code: (p1 is the name of the database)
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/p1');
index.js code to store in DB:
/* GET New User page. */
router.get('/addnew', function(req, res) {
res.render('addnew', { title: 'Add New Theatre' });
});
/* POST to Add User Service */
router.post('/addnew', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var theatrename = req.body.TheatreName;
var screen = req.body.Screen;
var latitude = req.body.Latitude;
var longitude = req.body.Longitude;
var city = req.body.City;
// Set our collection (Theatre is the name of the collection)
var collection = db.get('Theatre');
// Submit to the DB
collection.insert({
"TheatreName" : theatrename,
"Screen" : screen,
"Latitude" : latitude,
"Longitude" : longitude,
"City" : city,
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
});
module.exports = router;
This is my jade code:
extends layout
block content
h1= title
form#formAddUser(name="adduser",method="post",action="/adduser")
p Thearte Name:
input#inputName(type="text", name="ThearteName")
br
p Screen :
input#inputScreen(type="text", name="Screen")
br
p Latitude:
input#inputUserLat(type="text", name="Latitude")
br
p Longitude:
input#inputlong(type="text", name="Longitude")
br
p City:
input#inputCity(type="text", name="City")
br
br
button#btnSubmit(type="submit") submit
If I were you I will try to do this:
show in console that vars from "req.body.VAR" are send correctly.
For example
router.post('/addnew', function(req, res) {
console.log(req.body.Screen);
Then, I will try to add some data to the BD for example:
collection.insert({
"TheatreName" : "Fakename",
"Screen" : "Fakescreen",
"Latitude" : "0",
"Longitude" : "0",
"City" : "Fakecity",
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
If you can see the result in your BD, all is OK (else, is in connection or something similar).
I hope my answer will help you!
Related
My Schema look like this
var Company ={
Name
Email
Location
Industry
Creator
PostedJobs : [{
JobName
JobType
JobLocation
JobSalary
Applicants : [{
Name
Status
}]
}]
}
to push job here is my route code which is working
router.post('/:name' , isLoggedIn , function(req , res , next) {
var JobName = req.body.JobName;
var JobType = req.body.JobType;
var JobLocation = req.body.JobLocation;
var Salary = req.body.Salary;
var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalary:Salary};
var name = req.params.name;
Company.findOne({Name : name}).then(function(Company) {
Company.PostedJobs.push(postedJob);
Company.save();
req.flash('sucess_msg' , 'Job Added Sucessfully');
res.render('dashboard',{
"Company" : Company
});
});
});
now i want to push applicants on apply button
apply code is
router.get('/:id/apply' , isLoggedIn , function(req , res , next) {
var appicant = { Name : req.user.FirstName,
Status : "Applied"
};
Company.find({'PostedJobs._id' : req.params.id}).then(function(job) {
Company.PostedJobs.Applicants.push(applicant);
Company.save();
req.flash('sucess_msg' , 'Job Added Sucessfully');
res.redirect('/jobs');
});
});
i also tried
which is not working and i wont know what to do with this
Can you try this? when pushing applicants.
Company.PostedJobs[0].Applicants.push(applicant);
my main issue is how do this architecture - if a user creates a new list in database and there is a separate collections for storing lists ,then i should redirect him when he want to access a specific list where he can store his contacts by assigning him some collection in database, now the problem comes for me, if there are 'n' lists of a specific user for saving his contacts by categorizing in to lists based on his need , then how should i implement this architecture any suggestions ? or there's a mistake with what i have done so far ? any corrections ?
i am using mongodb,nodejs with express framework
What i have so far done is manually i was able to create a new list and allocate a collection for it so that user can add his contacts in that list.
But creating collections manually for each and every list is not possible so i am searching for a method where we can automatically create a new collection on demand.
Is there any method to create n collection or n sub collections in mongodb ?
This is my js file for adding contacts in a collection , where i have stored those contacts in two separate list with separate collection for each list.
var express = require('express');
var router = express.Router();
var $ = require("jquery");
var mongoose = require('mongoose');
/* GET New User page. in list 1 */
router.get('/mylist', function(req, res) {
res.render('mylist', { title: 'Go To My-List' });
});
router.post('/delcontact', function(req, res){
console.log('Using delcontact');
var db = req.db;
var collection = db.get('golists');
console.log('Got this : ' + JSON.stringify(req.body));
var delcontact = req.body;
var emails = Object.keys(delcontact).map(function(k) { return delcontact[k] });
for(var z=0; z<emails.length; z++){
//console.log('email: \n' + emails[z]);
collection.remove({email: emails[z]},
function(err, doc, z) {
if (err)
res.send('delete unsuccessfull');
else {
console.log('Selected contacts deleted');
}
});
res.send({redirect: '/userlist2'});
var collection = db.get('golists');
};
});
/* POST to Add User Service */
router.post('/addusers', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var firstName = req.body.firstname;
var lastName = req.body.lastname
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('golists');
// Submit to the DB
collection.insert({
"firstname" : firstName,
"lastname" : lastName,
"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 {
// If it worked, set the header so the address bar doesn't still say /adduser
res.location("mailinglist");
// And forward to success page
res.redirect("mailinglist");
}
});
});
/* GET Userlist page. */
router.get('/mailinglist', function(req, res) {
var db = req.db;
var collection = db.get('golists');
collection.find({},{},function(e,docs){
res.render('userlist2', {
"userlist2" : docs
});
});
});
/* this is for list 2 */
router.get('/mylist2', function(req, res) {
res.render('mylist2', { title: 'Go To My-List' });
});
router.post('/addusers2', function(req,res){
//Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var firstName = req.body.firstname;
var lastName = req.body.lastname
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('golists2');
// Submit to the DB
collection.insert({
"firstname" : firstName,
"lastname" : lastName,
"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 {
// If it worked, set the header so the address bar doesn't still say /adduser
res.location("mailinglist2");
// And forward to success page
res.redirect("mailinglist2");
}
});
});
/* GET Userlist page. */
router.get('/mailinglist2', function(req, res) {
var db = req.db;
var collection = db.get('golists2');
collection.find({},{},function(e,docs){
res.render('mailinglist2', {
"mailinglist2" : docs
});
});
});
router.post('/delcontact2', function(req, res){
console.log('Using delcontact');
var db = req.db;
var collection = db.get('golists2');
console.log('Got this : ' + JSON.stringify(req.body));
var delcontact = req.body;
var emails = Object.keys(delcontact).map(function(k) { return delcontact[k] });
for(var z=0; z<emails.length; z++){
//console.log('email: \n' + emails[z]);
collection.remove({email: emails[z]},
function(err, doc, z) {
if (err)
res.send('delete unsuccessfull');
else {
console.log('Selected contacts deleted');
}
});
res.send({redirect: '/mailinglist2'});
var collection = db.get('golists2');
};
});
this is my file for creating new lists in some collection
router.get('/newlist',function(req,res){
res.render("newlist" ,{titile:'Add new list'}) ;
});
router.post('/addlist',function(req,res){
var db= req.db;
var listname=req.body.listname;
var collection=db.get("lists");
collection.insert({
"listname":listname
}, function (err,doc) {
if(err) {
res.send("There was a problem adding new list to database");
}
else {
res.location('lou');
res.redirect('lou');
}
});
});
router.get('/lou',function(req,res){
var db=req.db;
var collection=db.get("lists");
collection.find({},{},function(e,docs){
res.render('lou', {
"lou" : docs
});
});
});
router.get('/drop', function(req, res) {
res.render('drop', { title: 'Go To My-List' });
});
my jade file for this is
body
nav.navbar.navbar-default
.container-fluid
ul.nav.navbar-nav
li.active
a(href='/mailinglist')
| List 1
span.sr-only (current)
|
li
a(href='/mailinglist2')
| List 2
tbody
ul
p Import Contact From Your DB
a(href='/upload2') Go
table.table#stable
caption User Contact Details
|
thread
tr
th #
|
th FirstName
|
th LastName
|
th Email ID
|
each user, i in userlist2
tr(id=i)
td
input.contactID(type='checkbox')
td
| #{user.firstname}
td
| #{user.lastname}
td(id='email'+i)
| #{user.email}
button.btn.btn-danger#delete-button Delete Selected Contacts
First of all, this doesn't sound like a good idea. It would be much better when you have one collection for all lists of all users. The problem with having too many collections is that MongoDB doesn't offer any tools for selecting data from more than one collection at a time. So when you want to query data from multiple collections, you will have to perform multiple queries, which is very unperformant.
However, when you are determined to cling to this architecture, MongoDB automatically creates a collection when you insert data into a collection-name it doesn't know.
I'm trying to store the rowset from the query below into a variable so I can play it into the view and loop through it.
I'm getting results from the DB, and can console.log them in the db.each block, and I thought I could generate my JSON object below and then store it - but it's not setting it for some reason and var data = "" just returns an empty string.
I am a bit baffled as to why - does anyone know where I am going wrong please?
Thank you for taking the time to read.
var express = require('express');
var router = express.Router();
var db = require('../lib/db.js');
/* GET contacts listing. */
router.get('/', function(req, res) {
var data = "";
db.serialize(function() {
var rowset = db.each("SELECT b.forename, b.surname FROM contacts a, contact_attributes b WHERE a.contact_id = b.contact_id", function(err, row) {
data = ' { "'+row.contact_id+'" : [ { "forename" : "'+row.forename+'", "surname" : "'+row.surname+'" } ] } ';
});
});
res.render('contacts', {
title: "Contacts",
active: "contacts",
contacts: JSON.stringify(data)
});
});
module.exports = router;
The database query runs asynchronously, executing the callback function once the query returns. Therefore, res.render is called after data gets set to empty string, but before it gets set to the result set.
Also, there is no need to JSON.stringify a string that you have already built as JSON.
The code executes as follows:
var data = "";
db.serialize
var rowset = db.each
res.render
DB query returns.
db.each callback function executes, which sets data based on the result set.
Try this:
db.serialize(function() {
var rowset = db.each("SELECT forename, surname FROM contacts a, contact_attributes b WHERE a.contact_id = b.contact_id", function(err, row) {
var data = ' { "'+row.contact_id+'" : [ { "forename" : "'+row.forename+'", "surname" : "'+row.surname+'" } ] } ';
res.render('contacts', {
title: "Contacts",
active: "contacts",
contacts: data
});
});
});
});
or, avoid the manual JSON stringification:
db.serialize(function() {
var rowset = db.each("SELECT forename, surname FROM contacts a, contact_attributes b WHERE a.contact_id = b.contact_id", function(err, row) {
var data = {};
data[row.contact_id] = [
{
forename: row.forname,
surname: row.surname
}
];
res.render('contacts', {
title: "Contacts",
active: "contacts",
contacts: data
});
});
});
});
I'm encoutering an error when using a Mongoose Model in my program.
I've did that in the beginning of my code :
var Schema = mongoose.Schema;
mongoose.connect('xxxxx');
I used a first schema called userSchema to connect/sign up a user.
I've this code, which should do a random on the field Bonus of my DB. But when I go to the randTest page, I have this error. How can I fix it ?
app.get('/randTest', function(req,res)
{
var bonusSchema = new Schema({
bonus : [String]
});
var bonusModel = mongoose.model('Plateau', bonusSchema);
var query = bonusModel.find(null);
query.exec(function (err, allBonus){
if(err) { throw err;}
var rand = Math.floor((Math.random() *allBonus.length));
var result = allBonus[rand-1];
});
res.render('randTest', {result: result});
});
In my Jade file I've just :
extends layout
block content
script.
alert({#result});
Move the bonusModel definition outside of app.get so that it's only called once:
var bonusSchema = new Schema({
bonus : [String]
});
var bonusModel = mongoose.model('Plateau', bonusSchema);
app.get('/randTest', function(req,res)
{
var query = bonusModel.find(null);
...
});
I'm new to node and mongodb and am trying to render a database query in a template, but I get the error that the property is undefined:
Cannot read property 'firstname' of undefined
Here's my index.js file:
var dburl = 'localhost/olpdb';
var collections = ['users'];
var db = require('mongojs').connect(dburl, collections);
var currentUsers = db.users.find();
exports.index = function(req, res){
res.render('index', currentUsers);
};
In the index.jade template, I've got:
#{currentUsers.firstname}
I've queried the database separately and know that there is a record:
> db.users.find()
{ "firstname" : "andy", "lastname" : "johnson", "email" : "andy#johnson.com", "_id" : ObjectId("51adf8a8c58996cf0c000001") }
Can anyone help me with what I'm doing wrong? I'm trying to pass the object to the template so that I can extract the data.
In your code, currentUsers is probably an API object (a Query or similar). In order to use the query's result, you need to use a callback:
exports.index = function(req, res){
db.users.find(function(err, currentUsers) {
res.render('index', {
currentUsers: currentUsers
});
});
};
Now you can use the currentUsers array from your Jade template:
#{currentUsers[0].firstName}