How to solve insertOne is not a function problem - node.js

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 ..

Related

MongoDB Node.js issue with "Callbacks are deprecated"

Hello I have issue with MongoDB code, it make some methods like this (image below):
enter image description here
`
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("mydb");
var mysort = { name: 1 };
dbo.collection("customers").find().sort(mysort).toArray(function (err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
`
and when I try read error, it say:
(method) MongoClient.connect(url: string, callback: Callback): void (+3 overloads)
#deprecated — Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance
The signature '(url: string, callback: Callback): void' of 'MongoClient.connect' is deprecated.ts(6387)
mongodb.d.ts(4733, 9): The declaration was marked as deprecated here.
No quick fixes available
I tried reinstall it, or install older version and still same, I do connection same like in documentation.
Tried add (url,{ useUnifiedTopology: true }, and still same
Someone know what can be issue?
Try version 4.0.0
const MongoClient = require('mongodb').MongoClient;
// Connect to the MongoDB server
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
if (err) throw err;
// Get the sample database
const db = client.db('sample');
// Get the collection
const collection = db.collection('test');
// Insert a document
collection.insertOne({ name: 'John', age: 30 }, function(err, result) {
if (err) throw err;
console.log(result);
// Close the connection
client.close();
});
});
Let me know if you still have the same error .

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

Cannot insert document MongoDB database

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

Find result based on id in mongo db using node.js

I want to find result from collection using node.js in mongodb. My code is as follows
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
collection.findOne({_id:req.body.Id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
I am not able to get required result.Getting error collection is not defined.
Try convert id to ObjectId:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
db.collection('collectionName').findOne({_id:new ObjectID(req.body.Id)},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
You need to define which collection you're going to query:
db.collection('CollectionName').findOne({_id: req.body.Id}, function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
db.close();
});
Node.js MongoDB Driver API - findOne

Resources