I am trying to simply insert an entry in a MongoDB collection using Nodejs. Here is my code:
code:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');
db.collection('Todos').insertOne({
text: 'Something to do',
completed: false
}, (err, result) => {
if (err) {
return console.log('Unable to insert todo', err);
}
console.log(JSON.stringify(result.ops, undefined, 2));
});
db.close();
});
When I run the code, it showing the following error:
error:
TypeError: db.collection is not a function
Uninstalling existing mongodb package and reinstalling using the following commands resolved the issues
npm uninstall mongodb --save
npm install mongodb#2.2.33 --save
Version MongoDB >= 3 - That database variable is actually the parent object of the object you are trying to access. If u using mongo 3+:
const myDb = db.db('YourDatabase')
myDb.collection('YourDatabase).insertOne ....
you can rewrite your code as follow
MongoClient.connect(url,(err,db) =>{
const database= db.db('TodoApp')
database.collection('Todos').insertOne({})
}
The reason for this error is the version of the NodeJs Driver. TypeError: db.collection is not a function. If the version is > 3.0.1 then you have to change the db to client. For more info check this page, it helped me!
[db.collection is not a function when using MongoClient v3.0
Hope that helps!
Related
I have created a Redis MemoryDB cluster with 2 nodes in AWS:
I connect to it using redis node library v4.0.0 like this:
import { createCluster } from 'redis';
(async () => {
const REDIS_USERNAME = 'test-username';
const REDIS_PASSWORD = 'test-pass';
const cluster = createCluster({
rootNodes: [
{
url: `rediss://node1.amazonaws.com:6379`,
},
{
url: `rediss://node2.amazonaws.com:6379`,
},
],
defaults: {
url: `rediss://cluster.amazonaws.com:6379`,
username: REDIS_USERNAME,
password: REDIS_PASSWORD,
}
});
cluster.on('error', (err) => console.log('Redis Cluster Error', err));
await cluster.connect();
console.log('connected to cluster...');
await cluster.set('key', 'value');
const value = await cluster.get('key');
console.log('Value', value);
await cluster.disconnect();
})();
But sometimes I get the error ReplyError: MOVED 12539 rediss://node2.amazonaws.com:6379 and I cannot get the value from the key.
Do you have any idea if there is something wrong with the configuration of the cluster or with the code using redis node library?
Edit:
I tried it with ioredis library and it works, so it's something wrong with the redis library.
Node.js Version: 16
Redis Server Version: 6
I had created an issue to redis library, so it's going to be solved soon with this PR.
I am trying to connect remote ibm db2 with node js in mac machine but I'm getting following error
[Error: [IBM][CLI Driver] SQL1598N An attempt to connect to the database server failed because of a licensing problem. SQLSTATE=42968
] {
error: '[node-ibm_db] SQL_ERROR',
sqlcode: -1598,
message: '[IBM][CLI Driver] SQL1598N An attempt to connect to the database server failed because of a licensing problem. SQLSTATE=42968\n',
state: '42968'
}
And this is how I'm trying to connect
function db2Connection() {
var ibmdb = require('ibm_db');
var connStr = "DATABASE=dbname;HOSTNAME=mydb.ibm.com;UID=userid;PWD=password;PORT=447;PROTOCOL=TCPIP";
ibmdb.open(connStr, function (err,conn) {
if (err) return console.log(err);
conn.query('SELECT * FROM T_Name FETCH FIRST 6 ROWS ONLY', function (err, data) {
if (err) console.log(err);
else console.log(data);
conn.close(function () {
console.log('done');
});
});
});
}
db2Connection();
I went through some docs regarding that error but did not get any solution. Can anyone help on how to achieve this.
I'm trying to connect to mongodb created by MongoLab, but it always seems to fail.
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>#ds123854.mongolab.com:12345/the_db');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
});
mongoose.connection.on('error', function (err) {
console.log('Could not connect to mongo server!');
console.log(err);
});
// check if mongoose connected; 0 = no; 1 = yes; 2 = connecting; 4 = disconnecting
console.log("mongoose connection: " + mongoose.connection.readyState);
I get the log:
mongoose connection: 2
Could not connect to mongo server!
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
I tried to check the password, so I did the following in my console:
> mongo ds123854.mongolab.com:12345/the_db -u <dbuser> -p <dbpassword>
MongoDB shell version: 3.0.7
connecting to: ds123854.mongolab.com:12345/the_db
rs-ds123854:PRIMARY> db.mynewcollection.insert({ "foo": "bar"})
WriteResult({ "nInserted" : 1 })
rs-ds123854:PRIMARY> db.mynewcollection.find()
{ "_id" : ObjectId("563c1913504f0ab5cb96d74c"), "foo" : "bar" }
The username and password seem right and I can see that the insert command did put something into the database.
I am hosting my server in localhost, so I believe that's the problem. What sort of things am I missing in my configuration?
Solution: Ensure that your version of Mongoose is up to date.
In my case, I was using version 3.6.13, but the current version is 4.2.4
If you specified your mongoose version, just update your package.json file and use command line npm update
I created a simple demo using mongoose, which works perfectly on localhost:
mongoose.connect('mongodb://localhost/mindmap', function(err, next) {
if(err) return next(err);
console.log('database connected');
});
It fetches data with a simple find:
/* GET mindmaps. */
router.get('/', function(req, res, next) {
Mindmap.find(function (err, mindmaps) {
if (err) return next(err);
res.json(mindmaps);
});
});
And adds data through socket connection
// handle adding new mindmaps
socket.on('mindmap.add', function (data) {
Mindmap.create(data, function (err, mindmap) {
if (err) throw err;
mindmaps.push(mindmap);
io.sockets.emit('mindmap.add', mindmap);
});
});
Now all of this is working fine locally.
Today I installed npm, bower, the app itself and MongoDB on my CentOS 6.5 VPS. I started the mongo service and on the server changed app.js to connect to the correct ip/port:
mongoose.connect('mongodb://127.0.0.1:27017/mindmap', function(err, next) {
When I start the app with node bin/www the connect does not throw any errors and simply states that the database is connected. The /mindmap gives an empty array (which is logical at this point). Adding a new mindmap through the socket connection even emits a proper mindmap object and the html will display it. There's no errors, but also nothing is saved and on a refresh it starts empty again. Also in the mongo shell there's nothing in the collection.. and if I add something manually I can't see it in /mindmap.
Full client-side code is on http://mindmap.solidwebcode.com:3000/mindmap
For reference this is the model:
var mongoose = require('mongoose');
var SubjectSchema = new mongoose.Schema({
title: String,
x: Number,
y: Number,
w: Number,
h: Number,
parent: mongoose.Schema.Types.ObjectId
});
var MindmapSchema = new mongoose.Schema({
name: String,
theme: String,
subjects: [SubjectSchema],
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Mindmap', MindmapSchema);
I installed mongodb using:
sudo yum --enablerepo=epel install mongodb mongodb-server
sudo service mongod start
Also starting mongo works as expected, although there's some warnings:
Server has startup warnings:
2015-05-04T13:42:08.955+0200 [initandlisten]
2015-05-04T13:42:08.955+0200 [initandlisten] ** WARNING: You are running in OpenVZ which can cause issues on versions of RHEL older than RHEL6.
2015-05-04T13:42:08.955+0200 [initandlisten]
I have never before installed mongo on a VPS and used it. Am I missing something trivial?
The problem is not MongoDB is not working, but rather that the socket connection was started to localhost:3000, which is not the same as the external server.. so while nothing happends on the remote server, the local server was accepting the socket connection and adding new records in it's own database.
Solution was simple: change the socket connect to a remote address.
I installed MongoDB in my machine and I'm able to start mongod and connect to the db using the mongo command. I even imported some data in the mycol collection of the mydb db:
$ sudo start mongodb
mongodb start/running, process 31008
$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use mydb
switched to db mydb
> db.mycol.count();
5730
> ^C
bye
But now if I want to access the db via node.js it doesn't work anymore, I get a TypeError.
I try this code (UPDATED):
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/mydb', function(err, db) {
if(err) throw err;
console.log("connected!");
});
This is based on the npm module mongodb, I also tried mongoose and mongojs, each time with the same result. As soon as I want to connect to the database, I get a TypeError.
$ node mngclient.js
Failed to load c++ bson extension, using pure JS version
events.js:172
throw TypeError('type must be a string');
^
TypeError: type must be a string
at TypeError (<anonymous>)
at EventEmitter.once (events.js:172:11)
at Server.Base._registerHandler (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/base.js:387:23)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/server.js:410:12)
at EventEmitter.emit (events.js:91:17)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:111:15)
at EventEmitter.emit (events.js:97:17)
at Socket.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection.js:297:10)
at Socket.EventEmitter.emit (events.js:116:20)
at Object.afterConnect [as oncomplete] (net.js:848:10)
UPDATE:
The version of the mongodb npm package is 1.3.23
npm outdated shows no output, so I guess my packages are up-to-date
Using mongoose with the following very simple code brings up the exact same error:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
UPDATE II:
I still couldn't resolve this issue on my machine
I setup the whole project in a virtual machine using vagrant. It works like a charm.
You should read the document , your trying to start a server(I'm not sure why?) here is an example on connecting to the mongo database you already have running :
MongoClient.connect('mongodb://localhost:21017/myDb', function(err, db) {
"use strict";
if(err) throw err;
...//your code
});
Step 1: npm install mongodb
Step 2: create a file, name it suppose : app.js
Paste the following content into the file:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'myDB';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
Step 3 : node app.js
Step 4: run mongod and mongo, check updated db list using show dbs
Database will be created and a collection named 'documents' will be added over there.