i want to pass email in postman and want to print the fetched json data to console. but it is not fetching any data. so help me to solve this issue
mongoconnect.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.connection=function(){
if(dbo!=null) return
MongoClient.connect(url, function(err, db) {
if (err) throw err;
dbo = db.db("hospital_api");
});
}
var get = function (){
return dbo;
}
exports.email=function(r){
get().dbo.collection("doctor").find({"email":r}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
return result;
})
}
doctor.js
var express = require('express');
var router = express.Router();
var bodyParser = require("body-parser");
var validator = require('validator');
var mongo= require('./mongoconnect')
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/',function(req,res)
{
d=mongo.email(req.body.email)
console.log(d);
})
module.exports = router;
In export.email, you have a typo
exports.email = function(r) {
get().collection("doctor").find({"email":r}) // no ".dbo" after get()
Related
I have created a service in node.js for basic crud operations. However when I start service it throws Route.get() requires a callback function but got a [object Undefined] error. I am not able to figure out where the error is.
Here is my code.
Models:
agreement_master.js.
const mongoose = require('mongoose');
const agreementmaster = mongoose.Schema({
ClientId:{type:Number},
UserId:{type:Number},
StartDate:{type:Date},
});
var Agreement = module.exports =
mongoose.model('Agreement',agreementmaster);
module.exports.addmAgreement=function (data,callback){
data.save(callback);
}
module.exports.getallmAgreement= function (data,callback){
var query = {status:true};
Agreement.find(query, callback);
}
routes:
agreement_master.js
var express = require('express'),
router = express.Router(),
magreement = require('../controller/agreement_master');
router.post('/addmAgreement', magreement.addmAgreement);
module.exports = router;
Controller:
agreement_master.js
const Agreement= require('../models/agreement_master');
exports.addmAgreement = function (req, res){
var data = JSON.parse(JSON.stringify(req.body));
var agreement = new Agreement(data);
agreement.ClientId = req.body.ClientId;
agreement.UserId= req.body.UserId;
agreement.StartDate=new Date();
Agreement.addmAgreement(agreement, function (err, obj) {
if (err) return res.json({err, status:'error'});
if(obj){
return res.json({
message:'agreement added',
});
}
});
};
index.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressValidator = require('express-validator');
const cookieParser = require('cookie-parser');
mongoose.connect('mongodb://local/local-host')
const app = express();
error comes at this part in the below line:
const agreement = require('./routes/agreement_master');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(expressValidator());
app.use(cookieParser());
//Add Routes here
app.use('/agreement', agreement);
app.set('port', (process.env.PORT || 3001));
var server = app.listen(app.get('port'), function(){
console.log('Server Started on port ' + app.get('port'));
});
module.exports = app;
user module.exports instead of exports.
exports doest export anything and will not be used by require();
module.exports.addmAgreement = function (req, res){
var data = JSON.parse(JSON.stringify(req.body));
var agreement = new Agreement(data);
agreement.ClientId = req.body.ClientId;
agreement.UserId= req.body.UserId;
agreement.StartDate=new Date();
Agreement.addmAgreement(agreement, function (err, obj) {
if (err) return res.json({err, status:'error'});
if(obj){
return res.json({
message:'agreement added',
});
}
});
};
try this
router.post('/addmAgreement', function(req, res){
magreement.addmAgreement
});
instead of
router.post('/addmAgreement', magreement.addmAgreement);
In the code below, what is best way to pass information from app.js to choices.js ?
Currently, I put them all in a variable called answer.
Is that the best way to do it ?
Thank you.
These are the code in app.js:
var express = require("express");
var cors = require("cors");
var bodyParser = require("body-parser");
var app = express();
var sql = require('msnodesqlv8');
:
var choicesTerm = [];
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res, next) {
console.log(`${req.method} request for '${req.url}' -
${JSON.stringify(req.body)}`);
next();
});
var connStr = "Driver={SQL Server Native Client 11.0};....";
sql.open(connStr, function (err, conn) {
var pm = conn.procedureMgr();
pm.callproc('mySP',sessionID, function (err, results) {
:
pm.callproc('mySp2', function (err, results) {
:
if (results.length)
{
var row = results[0];
var Answers = [];
Answers = row.Answers.split("|");
for (var i = 0, len = Answers.length; i < len; i++) {
var answer = {value: Answers[i], description: Answers[i], question: row.text, detail: row.detail}; //--> pass information to choices.js
choicesTerm[i] = answer;
}
}
})
});
});
app.use(express.static("./public"));
app.use(cors());
app.get("/choices-api", function(req, res) {
res.json(choicesTerm);
});
These are the code in choices.js:
$(document).ready(function () {
$.getJSON('/choices-api', printTerms);
});
function printTerms(terms) {
var question = terms[0].question; //--> This is passed from app.js
var detail = terms[0].detail; //--> This is passed from app.js
}
Making this simple Node.js Express API I encountered an odd problem:
I am creating a model and inserting data into it and then saving it to my MongoDB. But the record is never saved but I also don't get any error. I have checked if MongoDB is running and both syslog for Node errors and mongod.log for MongoDB errors as well as my own Wilson debug.log file. All contain no errors.
I use postman to test the API and do get a response every time. It's just that the data does not get saved to MongoDB (I used the mongo console with db.collection.find() to check for inserted records).
Any idea why this could be happening?
my code:
api.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var https = require('https');
var fs = require('fs');
var winston = require('winston');
// Configure logging using Winston
winston.add(winston.transports.File, { filename: '/home/app/api/debug.log' });
winston.level = 'debug';
// Request body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Enable https
var privateKey = fs.readFileSync('path to private key');
var certificate = fs.readFileSync('path to cert file');
var credentials = {
key: privateKey,
cert: certificate
};
// ROUTERS
var router = express.Router();
var speciesRouter = require('./app/routes/speciesRouter');
router.use('/species', speciesRouter);
// Routes prefix
app.use('/api/v1', router);
// SERVER STARTUP
http.createServer(app).listen(3000);
https.createServer(credentials, app).listen(3001);
speciesRouter.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var Sighting = require('../models/sighting');
var winston = require('winston');
// Database connection
var dbName = 'dbname';
mongoose.connect('mongodb://localhost:27017/' + dbName);
var db = mongoose.connection;
db.on('error', function(err){
winston.log('debug', err);
});
router.route('/')
.post(function(req, res) {
var sighting = new Sighting();
sighting.user_key = req.body.user_key;
sighting.expertise = req.body.expertise;
sighting.phone_location = req.body.phone_location;
sighting.record_time = req.body.record_time;
sighting.audio_file_location = '/var/data/tjirp1244123.wav';
sighting.probable_species = [{species_name:'Bosaap', percentage:100}];
var error = '';
winston.log('debug', 'test');
// This does not get execute I suspect..
sighting.save(function(err) {
winston.log('debug', 'save');
if (err) {
winston.log('debug', err);
error = err;
}
});
res.json({
probable_species: probable_species,
expertise: req.body.expertise,
error: error
});
});
module.exports = router;
sighting.js (model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SightingSchema = new Schema({
user_key: String,
expertise: Number,
phone_location: { lat: Number, lng: Number },
record_time: Number,
audio_file_location: String,
probable_species: [{ species_name: String, percentage: Number }]
});
module.exports = mongoose.model('Sighting', SightingSchema);
Did you try updating your mongodb.
sudo npm update
You can try using promise.
return sighting.save().then(function(data){
console.log(data); // check if this executes
return res.json({
probable_species: probable_species,
expertise: req.body.expertise,
error: error
});
}).catch(function(err){
console.log(err);
});
One more thing dont use res.json outside the save function because in async code it will run without waiting for save function to complete its execution
I was wondering if there was a way to check for repeated values before entering them into the database using mongodb and mongoose. I am basically looking for a way to validate the data in a sense that the data is not repeated so I don't waste space. I was hoping someone could point me in the right direction or show me a a solution, thank you.
App.js:
var print = require('./print');
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
app.listen(config.port, function() {
print(`listening on ${config.port}`);
})
MongoClient.connect(config.localUrl, function(err, db) {
if(err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collection = db.collection('users');
app.post('/post', function(req, res) {
var name = req.body.name
var email = req.body.email
res.send(`You sent the name ${name} and the email ${email}`);
var user1 = {};
user1.name = name;
user1.email = email;
//validate no repeated values
collection.insert(user1, function(err,result){
if (err) {
console.log(err);
} else {
console.log('The Results', result);
db.close();
}
})
})
})
You Can use $setOnInsert
https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#op._S_setOnInsert with upsert:true.
I am trying to get response data from model(database) to controller
here is model
var database = require('../config/db');
exports.getAllBatch = function(done) {
database.query('SELECT batchName from batch', function (err, rows) {
if (err) return console.log(err);
else {
console.log(null, rows);
return rows;
}
})
};
here is controller
code to access data from model.
var express = require('express');
var router = express.Router();
var batch=require('../models/BatchModel');
var myParser = require("body-parser");
var app = express();
router.get('/getbatch', function(req, res, next)
{
var resp=batch.getAllBatch();
res.send(resp);
//not displaying anything on browser
});
});
How I get response on browser please guide me.Thank you in advance.
That is good code, the only thing missing is setting the body parser you have required
app.use(myParser.json())
Your functions are using a callback pattern, but you're not calling or checking the callbacks.
Model
var database = require('../config/db');
exports.getAllBatch = function(done) {
database.query('SELECT batchName from batch', function (err, rows) {
if (err) {
console.log('Err', err);
return done(err);
}
else {
console.log('Rows', rows);
return done(null, rows);
}
});
};
Controller
var express = require('express');
var router = express.Router();
var batch=require('../models/BatchModel');
var myParser = require("body-parser");
var app = express();
router.get('/getbatch', function(req, res, next) {
batch.getAllBatch(function(err, rows) {
if (err) {
res.status(500).send(err);
} else {
res.send(rows);
}
});
});