MongoError: Unsupported OP_QUERY command: insert - node.js

I have been new to MongoDB and I am trying to connect mongodb using nodejs application.
whenever i try to run the nodejs file an error is being raised.
MongoError: Unsupported OP_QUERY command: insert. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'conFusion';
const client = new MongoClient(url);
client.connect()
.then((client) => {
console.log('Connected correctly to server');
const db = client.db(dbName);
const collection = db.collection('dishes');
collection.insertOne({name: "Uthapizza", description: "test"})
.then((result) => {
console.log('Insert Document:\n', result.ops);
return collection.find({}).toArray();
})
.then((docs) => {
console.log('Found Documents:\n', docs);
return collection.deleteMany({});
})
.then((result) => {
console.log('Deleted Documents:\n', result);
return client.close();
})
.catch((err) => console.log(err));
})
I have been using mongoDB latest version 6.0 and i am not able to perform the insertion operation using my node application.
Connected correctly to server
MongoError: Unsupported OP_QUERY command: insert. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal
at C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\pool.js:593:63
at authenticateStragglers (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\pool.js:516:16)
at Connection.messageHandler (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\pool.js:552:5)
at emitMessageHandler (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\connection.js:309:10)
at Socket.<anonymous> (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\connection.js:452:17)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
ok: 0,
errmsg: 'Unsupported OP_QUERY command: insert. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal',
code: 352,
codeName: 'UnsupportedOpQueryCommand'
}
Please Help Me with this Problem and Please Mention The Solution. What Should I do To perform the operation as it is not working and op_query is deprecated in latest version.

The error says what you need to do (ie use latest mongo node driver). Latest servers stopped supporting legacy OP_INSERT/OP_QUERY wire protocols

Related

Error: read EINVAL when connecting to MongoDB with mongoose and SSL

When I try to connect to my MongoDB that requires SSL, my NodeJs app crashes on the following method:
conn = await mongoose.connect(process.env.DB_HOST, {
tlsCAFile: __dirname + '/ca-certificate.crt',
useNewUrlParser: true,
useUnifiedTopology: true
})
and I get the following error in stderr.log:
events.js:377
throw er; // Unhandled 'error' event
^
Error: read EINVAL
at Pipe.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Socket instance at:
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
errno: -22,
code: 'EINVAL',
syscall: 'read'
}
The interesting this is that this works just fine on my local windows machine, but crashes when deployed to A2Hosting shared hosting.
Also I am able to connect successfully (even on A2hosting) when connecting without mongoose like so:
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db('egomenu');
console.log('connected successfully');
} finally {
await client.close();
}
I am using mongoose: ^6.3.1 and node: 14.20.1 on A2hosting.
I believe that the error is generated when trying to read the .crt file during connection; however cannot figure out what is causing it.
Any help would be greatly appreciated :)

Error connecting to Atlas Free Cluster (MongoDB)

TL;DR: Can't connect to Atlas Cluster even after doing exactly what docs said.
Hi, so I read the docs of getting started with Atlas and everything seemed nice & easy. I did follow the steps, created a free cluster, whitelisted my IP, and then tried to connect using their sample app:
const { MongoClient } = require("mongodb");
// Replace the following with your Atlas connection string
const url = "mongodb+srv://<username>:<password>#clustername.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true";
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
} catch (err) {
console.log(err.stack);
}
finally {
await client.close();
}
}
run().catch(console.dir);
But the following error occurred when I tried to execute with: node connect.js
PS C:\Users\marjo\Documents\mongoDB Atlas> node connect
(node:11352) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [remote-doc-shard-00-02-otc5a.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:46:25
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
at Connection.emit (events.js:315:20)
at processMessage (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:384:10)
at TLSSocket.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:553:15)
at TLSSocket.emit (events.js:315:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}]
at Pool.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\topologies\server.js:438:11)
at Pool.emit (events.js:315:20)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:561:14
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:1008:9
at callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:97:5)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:396:21
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:66:11
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
I tried changing the connection string with the one from Atlas: (because it was different from the docs by a tiny bit)
const uri = "mongodb+srv://Marjo:<password>#remote-doc-otc5a.mongodb.net/<dbname>?retryWrites=true&w=majority";
But still the same result. My password had a !character so I put %21 instead of it. I also replaced with cluster name (Remote-Doc) and test but it still failed.
I'd appreciate if you could help me!
I think that you are having a problem with the parse of your password, maybe it has special characters.
The best way to handle this is to change the way that you are connecting to pass the user and password as options.
You can follow the doc and change your MongoClient conection for something like this:
const mongoclient = new MongoClient(new Server("remote-doc-otc5a.mongodb.net", 27017));
// Listen for when the mongoclient is connected
mongoclient.open(function (err, mongoclient) {
// Then select a database
const db = mongoclient.db("dbname");
// Then you can authorize your self
db.authenticate('username', 'password', (err, result) => {
// On authorized result=true
// Not authorized result=false
// If authorized you can use the database in the db variable
});
});
And with mongoose you can do something like this:
mongoose.connect('mongodb+srv://#remote-doc-otc5a.mongodb.net/test?retryWrites=true&w=majority', {
user: 'USERNAME',
pass: 'PASSWORD',
useNewUrlParser: true,
useUnifiedTopology: true
})
Also, check if you are not using the account password instead of the cluster/database password.
You can follow this tutorial to check if you are using the correct one: MongoDB Atlas Setup - Digital Ocean.
I just changed the Atlas password to a simple one with no special characters, and the connection worked! I feel ashamed now

Node-Postgres SequelizeConnectionError: password authentication failed for user

I am developping a backend application with node and sequelize. My database is from postgresql.
When lauching the app, the database connection works fine, but when it tries to communicate with the database to read or update, it fails with a connection error:
password authentication failed for user "wushin".
Seems really weird to me because database connection has already been done, and password has been validated. Do you guys know what's happening ? Maybe an issue with pg module but I tried different versions.
Versions
Node: 10.17.0
Sequelize: 5.21.3
Postgres: 10.11
pg module: 7.17.1
-> This code works fine:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})
-> But this promise fails with SequelizeConnectionError:
models.Question.findAll()
.then(data => {
console.log('-> Succeeded data fetching\n')
console.log(data)
})
.catch(err => {
console.log('-> Failed data fetching\n')
console.log('Error', err)
})
Logs:
yarn run v1.19.2
$ node index.js
Example app listening on port 4000 or something!
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
- Trying to fetch data:
-> Failed data fetching
Error:
{ SequelizeConnectionError: password authentication failed for user "wushin"
at connection.connect.err (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:182:24)
at Connection.connectingErrorHandler (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/client.js:194:14)
at Connection.emit (events.js:198:13)
at Socket.<anonymous> (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/connection.js:128:12)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:287:12)
at readableAddChunk (_stream_readable.js:268:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'SequelizeConnectionError'
It seems that you pass no configurations to Sequelize but the host. The minimum configurations are host, port, databasename, dialect username, and password.
From the docs:
const Sequelize = require('sequelize');
// Option 1: Passing parameters separately const sequelize = new
Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});
// Option 2: Passing a connection URI const sequelize = new
Sequelize('postgres://user:pass#example.com:5432/dbname');
I finally fixed this. The issue was that with sequelize, requiring the models calls an index.js that is supposed to do the sequelize connection for you, using the config repository sequelize creates.
My connection to sequelize was working well but the one that was launched by requiring models had some bad information on my database.
Therefore I could not use the imported model to fetch data on the database.
I inserted good config information :
require('dotenv').config()
module.exports = {
development: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
},
test: {
url: process.env.DATABASE_TEST_URL,
dialect: 'postgres',
},
production: {
url: process.env.DATABASE_PROD_URL,
dialect: 'postgres',
},
}
And completely removed the line that I wrote myself:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
It is now the models/index.js that connects to the database with :
const sequelize = new Sequelize(process.env.DATABASE_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})

Error connecting to heroku postgres db in nodejs

It seems after my database was upgraded to 10.2 I'm unable to connect.
I'm using the pg 7.4.2 npm package.
To be clear, I have been connecting without issue for 6 months using the same connection string which had ?ssl=true appended to it.
I get this error connecting via Pool or Client.
AssertionError [ERR_ASSERTION]: false == true
at Object.exports.connect (_tls_wrap.js:1099:3)
at Socket.<anonymous> (/home/e/express/testpg/node_modules/pg/lib/connection.js:94:23)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at Socket.emit (domain.js:421:20)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at Socket.Readable.push (_stream_readable.js:213:10)
at TCP.onread (net.js:598:20)
I'm now hardcoding the full postgres connection string so there is no issue with env variables.
I've tried adding/removing ?ssl=true to the end of the connection string and adding/removing ssl:true from the constructor. I've also tried with and without promises. Same error no matter what on both local and deployed to heroku.
imports:
import { Pool, Client } from 'pg'
method 1:
let pool = new Pool({
connectionString: csnew,
ssl: true
})
pool.connect().then( client => {
console.log('connected')
})
.catch(e=> {
console.log(e)
})
method 2:
let pgclient = new Client({
connectionString: csnew,
ssl: true
})
pgclient.connect().then( () => {
console.log('connected')
}).catch(e=> {
console.log(e)
})
That's because v7.4.2 broke its SSL support. Here's the open issue.
You need to use strictly v7.4.1 till the issue is resolved.
UPDATE
Version 7.4.3 fixed the issue.

How to read directly from mongo slave using mongodb in nodejs

I am trying to read from a slave node but I get the following error.
MongoError: not master
at Function.MongoError.create (node_modules/mongodb-core/lib/error.js:31:11)
at node_modules/mongodb-core/lib/topologies/server.js:777:66
at Callbacks.emit (node_modules/mongodb-core/lib/topologies/server.js:95:3)
at null.messageHandler (node_modules/mongodb-core/lib/topologies/server.js:249:23)
at Socket.<anonymous> (node_modules/mongodb-core/lib/connection/connection.js:265:22)
at emitOne (events.js:78:13)
at Socket.emit (events.js:170:7)
at readableAddChunk (_stream_readable.js:147:16)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:524:20)
Here is my code
var MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://slave.example.com/?slaveOk=true', {slaveOk: true}, (err, db) => {
if (err) { throw err }
d = db.db('order', {server: {slaveOk: true}})
d.eval('rs.slaveOk(); 1', (err, data) => {
if (err) { throw err }
console.log(data);
})
})
I am providing the complete list of hosts in the connection string because the node that is running this query only has access to the secondary MongoDB nodes.
When using the command line interface I am able to make queries as long as I run rs.slaveOk() before executing my query.
you can simply using below code
var collection1 = db.collection(currentCollection,{readPreference:'secondaryPreferred'});
for more details check Scaling Read Query Load

Resources