This is the code I have used to display the data from MongoDB. Getting error as "result is not defined". I have used the ID from MongoDB to display the result. But the stored data is not displayed on a separate page.
const express = require('express');
const app = express();
const ejs = require('ejs');
const assert = require('assert');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine','ejs');
app.set('')
var url = 'mongodb://localhost:27017';
app.get('/form',(req, res)=>{
res.render('form');
});
app.get('/data',(req, res)=>{
MongoClient.connect(url, (err, db)=>{
assert.equal(null, err);
var dbo = db.db("form");
var details = dbo.collection('usertable').find();
details.forEach((data)=>{
if(_id == 5b5ef0b8e0d9c23c2012cef2){
result = item;
return true;
}
})
});
res.render('customerdata',{item: result });
});
I was able to store the data with the below code:
app.post('/form/submit', (req, res)=>{
var item = {
title: req.body.title,
content: req.body.content,
author: req.body.author
};
MongoClient.connect(url, (err, db)=>{
assert.equal(null, err);
var dbo = db.db("form");
dbo.collection('usertable').insertOne(item, (err, result)=>{
assert.equal(null, err);
console.log('Inserted');
db.close();
});
});
res.redirect('/form');
});
app.listen(8080);
I believe you are facing this problem because
you are not referencing the objects inside the details array properly.
you are also not declaring the result object before entering the forEach loop. And this will result in the value of result being undefined.
Inside your forEach loop, each 'data' is an object. And hence you would have to refer to the id as data._id when you are checking it. Similarly data.item when you are trying to assign the value to result.
I have modified the code. This should work.
app.get('/data',(req, res)=>{
MongoClient.connect(url, (err, db)=>{
assert.equal(null, err);
var dbo = db.db("form");
var details = dbo.collection('usertable').find();
var result;
details.forEach((data)=>{
if(data._id == 5b5ef0b8e0d9c23c2012cef2){
result = data.item;
return true;
}
})
});
res.render('customerdata',{item: result });
});
Several things to note:
MongoClient.connect() is asynchronous, but you are calling res.render() synchronously.
Usually you do not want to initiate a connection to MongoDB at each request.
You should probably do dbo.collection('usertable').find().toArray(function(err, items) {...}); to access the data.
find is async, you have to return the result in the find callback, otherwise it's not defined :
app.get('/data',(req, res)=>{
MongoClient.connect(url, (err, db)=>{
assert.equal(null, err);
var dbo = db.db("form");
dbo.collection('usertable').find({}, function(err, details){
if(err)
{
res.render('customerdata',{item: null });
}
else
{
var result = null;
details.forEach((data)=>{
if(data._id.toString() == "5b5ef0b8e0d9c23c2012cef2"){
result = item;
}
})
res.render('customerdata',{item: result });
}
});
});
In addition your post request has the same mistake, your redirecting the user before the end of the insert operation. Correct code is :
app.post('/form/submit', (req, res)=>{
var item = {
title: req.body.title,
content: req.body.content,
author: req.body.author
};
MongoClient.connect(url, (err, db)=>{
assert.equal(null, err);
var dbo = db.db("form");
dbo.collection('usertable').insertOne(item, (err, result)=>{
assert.equal(null, err);
console.log('Inserted');
db.close();
res.redirect('/form');
});
});
});
Related
I would like to show the items from a SQL Server database with app.js as select-option on the jade page, but even though I have reached the number of items in the list, I get the result as either [object, object] or I can only display it as a number.
var express = require('express');
var router = express.Router();
var db = require('../config/db');
var sql = require('mssql');
var app = express();
var result;
var liste = [];
router.get('/doktorkayit', function (req, res, next) {
sql.connect(db, function (err) {
if (err)
console.log(err);
var request = new sql.Request();
request.query('select hastaneAdi from hastaneİsimleri', function (err, result) {
if (err) {
console.log(err);
res.send(err);
}
sql.close();
res.render('doktorkayit', {
liste: result.recordset
}, function (err, html) {
if (err)
console.log(err);
else
res.send(html);
});
});
});
});
select#drGorevliOlduguHastane.custom-
select(name='drGorevliOlduguHastane')
option(value="Seçiniz" selected='seçiniz') Seçiniz
-each item in liste
option(value="") item
I finally did.
res.render('doktorkayit', {
result: result.recordset
}, function (err, html) {
if (err)
console.log(err);
else
res.send(html);
});
-for item in result
option=item.hastaneAdi
I want to store an image in MongoDB using NodeJS. I have managed to insert an image in database, as an object with Buffer and img parameters. However, when I display it, I get an empty square instead. Anyone knows how to fix this?
Code :
var imgPath = '.public/images/image.png';
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
const assert = require('assert');
const dbName = 'database';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
var collectionClient = db.collection('collection1');
var store = {
img: {
data: Buffer,
contentType: String
}
};
store.img.data = fs.readFileSync(imgPath);
store.img.contentType = 'image/png';
collectionClient.insertMany([store], function (err, result) {
if (err) {
console.error('Insert failed', err);
} else {
console.log('Insert successful');
}
});
});
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("database");
dbo.collection("collection1").find({}).toArray(function(err, result) {
if (err) throw err;
router.get('/', function(req, res, next) {
res.contentType(result[0].img.contentType);
res.send(result[0].img.data);
});
db.close();
});
});
Instead, try this:
const download = Buffer.from((result[0].img.data).toString('utf-8','base64'));
res.end(download);
I am using ExpressJs + MongoDB and following code returns an error:
var db = monk(DB_URL);
app.use(function (req, res, next) {
req.db = db;
next();
});
app.get("/view_collections", function (req, res) {
var db = req.db;
db.listCollections().toArray(function (err, collections) {
console.log(collections);
});
});
The Error is:
TypeError: db.listCollections is not a function.
Other functions work perfectly. As an example, following code is working:
app.get('/testCollection', function (req, res) {
var collection = req.db.get('testData');
collection.find({}, {
limit: 300,
sort: {
timestamp: -1
}
}, (e, entries) => {
res.render('testView', {
entries: entries
});
});
});
I tried both db.getCollectionNames() and db.listCollections() but both return the same error but in the shell db.getCollectionNames() works.
Can someone please tell me how to get a list of MonogoDB collections inside,
app.get("/view_collections", function (req, res) {
//Here
});
I was facing the same error, a fix can be:
MongoClient.connect(url, function(err, client) {
const db = client.db(DBNAME)
db.listCollections().toArray(function(err, items) {
console.log(items)
//and u can loop over items to fetch the names
client.close();
});
})
Maybe this clarifies more:
const url = 'mongodb://localhost:27017/testdb';
MongoClient.connect(url, (err, client) =>
const db = client.db('testdb');
db.listCollections().toArray((err, collections) => {
console.log(collections);
client.close();
});
});
Notice, that there is the same 'testdb' in two lines:
const url = 'mongodb://localhost:27017/testdb';
const db = client.db('testdb');
Works the same when 'testdb' in url is missed:
const url = 'mongodb://localhost:27017/';
So basically, I am creating an inventory management app and want to show the updated record to the user in the sense not just the field that was updated but the whole document itself. My question is
*How do I show the whole updated record instead of the updated field to the user ? *
I am using postman to test this api. This is my code and those with comments are what I have tried.
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
module.exports = {
/*getCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
var doc = findMultiple(db,req,function() {
db.close();
});
});
res.send(doc)
}*/
postCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
updateRecord(db, req, function() {
db.close();
});
//findMultiple(db, req, function(){
//db.close();
//});
});
res.send('Record Found. Now updating this document...' + itemDescrip + '
Record Updated. This is the new record with updated issueQty '
+ issueQty )
}
}
var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany(
{ 'Item Description': req.body.itemDescrip},
{
$set: { 'Issued QTY': req.body.issueQty }
}
,
function(err, results) {
console.log(results);
console.log('Done');
callback();
});
};
/*var findMultiple = function(db, req, callback){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
var cursor = db.collection('documents').find({'Issued QTY': issueQty, 'Item
Description': itemDescrip});
cursor.each(function(err,doc){
assert.equal(err,null);
if(doc != err){
console.log('Successfully queried');
console.log(doc);
return doc;
} else {
callback();
}
});
};*/
I have tried putting another function findMultiple to get the data and show the updated record in the response but it did not work and have thought about linking my query api and the update api together but am not sure how to go about it. Any help is appreciated, thanks!
You need to:
Inside updateRecord(), call the callback with the results object of the update operation
Inside postCollection(), the callback passed to updateRecord() will have access to the results object
postCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
updateRecord(db, req, function(results) {
res.send('Document...') //Do what you want with results here
db.close();
});
});
var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany(
{'Item Description': req.body.itemDescrip},
{$set: { 'Issued QTY': req.body.issueQty }},
function(err, results) {
console.log(results);
console.log('Done');
callback(results); //pass results to the callback
});
};
I am using MongoDB to insert a record into the database, every time the post method is called. I know I do not want to connect to the db inside of the post function every time, but this is giving me errors? How can I correct this?
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db = function() {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
}
app.post('/rsvp', function (req, res) {
var item ={
name: req.body.name,
attending: req.body.attending,
};
insertItem(item);
res.sendFile(path.join(__dirname + '/confirm.html'));
})
function insertItem(item){
db.collection('rsvpList').insertOne(item, function(err, result){
assert.equal(null, err);
})
}
I am getting this error:
TypeError: Object function () {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
} has no method 'collection'
at insertItem (C:\Users\A587092\Documents\weddingWebsite\server.js:53:8)
at app.listen.host (C:\Users\A587092\Documents\weddingWebsite\server.js:38:4)
at Layer.handle [as handle_request] (C:\Users\A587092\Documents\weddingWebsite\node_modules\express\lib\router\layer.js:95:5)
The problem is your db does not point to the Mongo instance rather to a function!
Try this -
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db;
mongo.connect(url, function(err, connectedDB){
if (!err){
db = connectedDB;
}
});
You couldn't simply return a value from an asynchronous method:
You should use a callback function:
var connectDb = function(url, cb) {
mongo.connect(url, function(err, db){
if ( err ) {
cb( err );
}
cb(null, db);
});
};
Usage:
function insertItem(item) {
connectDb(url, function(error, db) {
if ( error ) {
throw error;
}
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
});
}
Or a promise:
var connectDb = function(url) {
return new Promise(function(resolve, reject) {
mongo.connect(url, function(err, db){
if ( err ) {
reject(err);
}
resolve(db);
});
});
};
Usage:
function insertItem(item) {
connectDb(url)
.then(function(db) {
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
}, function(err) {
throw err;
});
}
I change the function name from db to connectDb because we want to connect to db and then doing something after connecting. and this way your code reads well.
Also note that here also your insertItem function doing an asynchronous task so if you need the result outside of this function you should implement a similar approach, i leave it to you ;)