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);
Related
I am trying to return all the entries from a mongodb collection from a nodejs.
I had written the function and it works if i console log the result i see all the objects from the colletion, but if i try to return the result i am getting undefined.
I cant figure it out why? I had also tried to JSON stringify and JSON parse after but still no success.
Here is my code:
`
const mongoUrl = "mongodb://192.168.8.156:27017/";
const getRoomReadings = function (id) {
MongoClient.connect(mongoUrl, function (err, db) {
if (err) throw err;
let dbo = db.db(`room${id}`);
dbo
.collection("env")
.find({})
.toArray(function (err, result) {
if (err) throw err;
return result;
});
});
};
// API RoomX route
app.get("/api/r:id", (req, res) => {
const rez = getRoomReadings(req.params.id);
console.log(rez);
});
`
I am using nodejs with express.
Please help me. Thanks in advance.
I had also tried to JSON stringify and JSON parse after but still no success.
I don't know why you created the connection each time you do the request but using promises will help you.
Example:
const mongoUrl = "mongodb://192.168.8.156:27017/";
const getRoomReadings = function (id) {
return new Promise((res, rej) => {
MongoClient.connect(mongoUrl, function (err, db) {
if (err) rej(err);
let dbo = db.db(`room${id}`);
dbo
.collection("env")
.find({})
.toArray(function (err, result) {
if (err) rej(err);
return res(result);
});
});
})
};
// API RoomX route
app.get("/api/r:id", async (req, res) => {
const rez = await getRoomReadings(req.params.id);
console.log(rez);
});
a better way to create a connection it creating a file call conn.js and inside that file create your connection
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db) {
return callback(err);
}
dbConnection = db.db(<db_name>);
console.log("Successfully connected to MongoDB.");
return callback();
});
},
getDb: function () {
return dbConnection;
},
};
initialize the connection and use getDb to get the connection
EDIT - BTW, I am trying to Insert 100 Tweets into the MongoDB database.
I am trying to insert the text of Tweets (using Twitter API) into a MongoDB database and I get TypeError: Cannot create property _id on string even after parsing. I bet that it may be an easy and dumb mistake to fix. My code is the following:
EDIT 2 - I edited the code to get the same error Im still having.
var Twitter = require('twitter');
var fs = require("fs");
var request = require("request");
var client = new Twitter({
consumer_key: ' ',
consumer_secret: ' ',
access_token_key: ' ',
access_token_secret: ' '});
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
var parser = { useNewUrlParser: true };
MongoClient.connect(url, parser, function(err, db) {
if (err) throw err;
console.log("Database created!");
var dbo = db.db("mydb");
dbo.createCollection("datos_sentimiento", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
MongoClient.connect(url, parser, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var cont = 0;
var params = {q: '#Avengers', count: 100, include_rts: 0, tweet_mode: 'extended', retweeted_status: 'extended'};
client.get('search/tweets', params, function(error, tweets, response) {
if (!error) {
//console.log(tweets);
for(var i=0; i < params.count; i++){
if(tweets.retweeted_status){
tweets = tweets.retweeted_status;
var tweet = (JSON.stringify(tweets.statuses[i])+"\n");
var string = tweet.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
console.log('hi');
}
else{
//console.log('hi2');
}
var tweet = (JSON.stringify(tweets.statuses[i].full_text));
var string = tweet.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
var string2 = (JSON.stringify(string)+"\n");
fs.appendFile("tweet.txt", string2, function (err) {
if (err) throw err;
//console.log('Saved!');
});
/*console.log(cont);
cont++;*/
var myobj = JSON.parse(string2);
console.log("hi "+myobj);
dbo.collection("datos_sentimiento").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
//console.log(i+'fdfdfdfdf');
}
}
});
});
The error shows the following message:
TypeError: Cannot create property '_id' on string 'RT #RobertDowneyJr Brace yourselves #Avengers InfinityWar hits the interwebs today httpstcoqvBQ3W8jvc'
Variable myobj is string in above case so, please make it to object like this {myobj}:
Previous: dbo.collection("datos_sentimiento").insertOne(myobj, function(err, res) {
Modify to : dbo.collection("datos_sentimiento").insertOne({myobj}, function(err, res) {
I found the solution. MongoDB needs (a must have!) to have a document (eg. text = {screen_name: name, text: text}). My correction is the following:
var text = JSON.parse(string2);
var myobj = {texto: text};
console.log("hi "+text);
dbo.collection("datos_sentimiento").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
I am not able to insert data into MongoDB database using insert method in Nodejs.
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
if (err) throw err;
// db gives access to the database
const myDb = db.db('learnyoumongo');
var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
docs.insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
})
db.close();
}
There is no output coming and connection to the data base is successful but no insertion of data is happening.
Try this will work for you .
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, dbobj) {
if (err) throw err;
// db gives access to the database
// const myDb = dbobj.db('learnyoumongo').collection('docs');
// var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
dbobj.db('learnyoumongo').collection('docs').insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
dbobj.close();
})
})
I figured out what the problem is. Seems like I forgot to add a parenthesis in the end:
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
if (err) throw err;
// db gives access to the database
const myDb = db.db('learnyoumongo');
var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
docs.insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
})
db.close();
})
You can use the following code to insert data into MongoDB using nodejs.
var mongo = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/learnyoumongo";
mongo.connect(url, function(err, db) {
if (err) throw err;
//access to the database
var myobj = { firstname: "Jhon", lastname: "Mackey" };
db.collection("docs").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("Data inserted");
db.close();
});
});
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 ;)
I want to export variable 'result_array' from './models/devices-client.js' below
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.dbadmin_uri, function (err, db) {
if (err) throw err;
// console.log('Successfully connected');
var collection = db.collection('repvpn2');
collection.find().toArray(function (err, result_array) {
// console.log('Found results:', result_array);
module.exports.Hosts = result_array;
db.close();
});
});
but when import in the other file it prints 'undefined' ?
var Hosts = require('./models/devices-client').Hosts;
console.log(Hosts);
let your module take an async function callback.
// JavaScript source code
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;
module.exports = function (callback) {
MongoClient.connect(config.dbadmin_uri, function (err, db) {
if (err) throw err;
// console.log('Successfully connected');
var collection = db.collection('repvpn2');
collection.find().toArray(function (err, result_array) {
// console.log('Found results:', result_array);
callback(err, result_array);
db.close();
});
});
}
require('./models/devices-client')(function callback(err,Hosts) {
//Hosts Here
});