Cannot insert document MongoDB database - node.js

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();
});
});

Related

Mongodb find not printing json data

In the code I am trying to find all documents with code UE19CS204.But in the console.log
a big message is printed not the JSON data.The findOne() is working but not find().
I don’t know what change to do to find all documents with code UE19CS204.
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);
dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here.
Use toArray(), you can finde the documentation here.
dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
Full example:
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) {
throw err;
}
client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
client.close();
});

How to solve insertOne is not a function problem

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';
MongoClient.connect(url, {useNewUrlParser: true}, function(err, db){
if(err) throw err;
var dbo = db.db('mydb');
var myObj = [{name: 'Company Inc', address: 'Highway 37'}];
dbo.createCollection('Customers').insertone(myObj, function(err, res){
if(err) throw err;
console.log('1 document inserted!');
db.close();
});
});
My code is not working, the error is insertOne is not a function. My mongoDB shell version is 3.4.18 and npm installed mongodb module is 3.1.10.
Try inserting your record without creating the collection, as insertOne will automatically create the collection if it does not exist.
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';
MongoClient.connect(url, {useNewUrlParser: true}, function(err, db){
if(err) throw err;
var dbo = db.db('mydb');
var myObj = [{name: 'Company Inc', address: 'Highway 37'}];
var collection = db.collection('Customers');
collection.insertOne(myObj, function(err, res){
if(err) throw err;
console.log('1 document inserted!');
db.close();
});
});
https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/
just check the case of letter o in your insertOne function ..

TypeError: Cannot create property '_id' on string... even after using JSON.Parse?? (MongoDB /Node.js / Twitter API)

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();
});

NodeJs And MongoDB

db.getCollection('Leave').find({},{_id:0 ,
Can_It_Be_carry_forwarded:1})
this is working perfectly in the MongoDb Client CMD But not in the Below Code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/Chatbot_Project";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Chatbot_Project");
dbo.collection('Leave').find({}, {Can_It_Be_carry_forwarded:1}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
db.close();
})
});
Your problem is the find method, you are missing the projection field.
If you want to retrive only the Can_It_Be_carry_forwarded field you need the following: {projection:{Can_It_Be_carry_forwarded:1, _id: 0}} as the second argument.
Solution from a similar question: https://stackoverflow.com/a/48294672/4120554
Documentation: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
Try this:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/Chatbot_Project";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Chatbot_Project");
dbo.collection('Leave').find({},{projection:{_id: 0, Can_It_Be_carry_forwarded:1}}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
db.close();
})
});

NodeJS - Image displayed from MongoDB as an empty square

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);

Resources