I have mongod running in one tab, mongo shell works perfectly in another.
Here is my code, I have mongoose version 5.9.10 installed in my project folder using npm and mongodb 3.5.6
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27071/fruitsDB", { useUnifiedTopology: true,useNewUrlParser: true, useFindAndModify:false, useCreateIndex:true });
const fruitSchema = new mongoose.Schema ({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit ({
name: "Apple",
rating: 8,
review: "gud"
});
fruit.save();
run, get a bunch of errors and warnings and no db is created according to mongo shell
Here is what the error I'm getting when I do node app.js in hyper
UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27071
at new MongooseServerSelectionError (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\node_modules\mongoose\lib\error\serverSelection.js:22:11)
at NativeConnection.Connection.openUri (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\node_modules\mongoose\lib\connection.js:823:32)
at Mongoose.connect (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (C:\Users\ahuja\Desktop\code\Web Development\fruitsProj\app.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:7980) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
mongoose
.connect("mongodb://localhost/fruitsDB", { useUnifiedTopology: true,useNewUrlParser: true, useFindAndModify:false, useCreateIndex:true })
.then(() => {
log.info("successfully connected to db");
})
.catch((err) => {
log.error("db connection failed " + err);
});
Related
When updating to Mongoose 6 with Mongodb nodejs driver version 4, I have the error below:
MongoInvalidArgumentError: No AuthProvider for DEFAULT defined.
at prepareHandshakeDocument (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:153:29)
at performInitialHandshake (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:63:5)
at /home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:25:9
at callback (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:244:9)
at Socket.connectHandler (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:282:9)
at Object.onceWrapper (events.js:519:28)
at Socket.emit (events.js:400:28)
at Socket.emit (domain.js:470:12)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:10)
From previous event:
at NativeConnection.Connection.openUri (/home/arch/git/project/node_modules/mongoose/lib/connection.js:778:19)
at /home/arch/git/project/node_modules/mongoose/lib/index.js:330:10
at promiseOrCallback (/home/arch/git/project/node_modules/mongoose/lib/helpers/promiseOrCallback.js:10:12)
at Mongoose._promiseOrCallback (/home/arch/git/project/node_modules/mongoose/lib/index.js:1151:10)
at Mongoose.connect (/home/arch/git/project/node_modules/mongoose/lib/index.js:329:20)
at connectToDb (/home/arch/git/project/core/configs/database.js:101:8)
at createServer (/home/arch/git/project/app.js:65:16)
at Object.<anonymous> (/home/arch/git/project/app.js:262:3)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
I don't have any authentication set up (this is my local development environment) so I don't understand where is the issue comming from. Here is the relevant connection code:
let connectionURL = 'mongodb://';
const connectionOptions = {
authSource: options.authSource,
};
if (options.user && options.password) {
connectionURL += `${options.user}:${options.password}#`;
}
connectionURL += `${options.host}/${dbName}?authSource=${options.authSource}`;
mongoose
.connect(connectionURL, connectionOptions, function onConnected(err) {
if (err) {
return cb(new Error(`Can not connect to database ${dbName}`));
}
return cb(null, mongoose.connection);
});
For a passwordless/userless connection, making sure the connection url doesn't contain authSource worked for me. This worked somehow before the version 4 of the driver, but not any more.
Also, either choose wether to pass options in the object or in the connection string. As the doc says:
Best practice is to put options that likely differ between development and production, like replicaSet or ssl, in the connection string, and options that should remain constant, like connectTimeoutMS or poolSize, in the options object
const connectionOptions = {};
if (options.user && options.password) {
connectionOptions.user = options.user;
connectionOptions.password = options.password;
connectionOptions.authSource = options.authSource;
}
const connectionURL = `mongodb://${options.host}/${dbName}`;
mongoose
.connect(connectionURL, connectionOptions, function onConnected(err) {
if (err) {
return cb(new Error(`Can not connect to database ${dbName}`));
}
return cb(null, mongoose.connection);
});
};
I am working on node.js.
node.js version is v14.1.0.
KingInfo.js
"use strict";
const db_module = require('../DB/db');
(async function(){
console.log("start");
let sql = [];
sql.push("SELECT count(*) as count");
sql.push(" FROM dbname.tablename");
let result = await db_module.query(sql.join(""));
console.log("result="+Object.entries(result));
console.log("end");
}());
db.js
"use strict";
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'databasename'
});
async function query(sql){
console.log("query.1");
await connection.connect((err) => {
console.log("connection.connect");
if (err) throw err;
});
return connection.query(sql, function (err, result, fields) {
console.log("connection.query.1");
if (err) throw err;
return result;
});
}
module.exports = {
query: query
}
I run node KingInfo.js then got the errors and logs:
start
query.1
(node:15792) UnhandledPromiseRejectionWarning: TypeError:
Cannot convert object to primitive value
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at E:\XXXXXX\XXXX\XXXX\XXXX\XXXXXXX\XXXXXXX\XXXXXXX\KingInfo.js:33:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:15792) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15792) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
connection.connect
connection.query.1
it seems stopped at this code: let result = await db_module.query(sql.join("")); because it doesn't have log for the code: console.log("result="+Object.entries(result)); and the rest.
I am new to async process, promis, await/async things. So my code related to async might cause this errer?
I should have asked in another post but I am not confident the code in the db module, either. If you have some advice for me how to fix it properly, please tell me.
This question was asked 8 month ago, but I will provide some advise for people who face such a problem. Well,
mysql library is callback-based-only, it's methods not return promises, if you need promises, then consider something like promise-mysql.
If you look at your output, you will see that after unhandledRejection error there are 2 lines printed, which are the console.log's from your connect and query callbacks, so, in the end, your query is performed successfully.
The thing with this error is that, object that is returned by connection.query call, contains some property, that can not be converted to primitive value, due to either being torn from the simple object prototype chain(i.e. something like ({}).__proto__ = null), or there are invalid overrides of Symbol.toPrimitive method or both of toString and valueOf methods.
Here is an example code with same error result:
const o = {}
o.toString = undefined
o.valueOf = () => ({}) // Must return primitive
const returnedByQuery = { o }
console.log("result " + Object.entries(returnedByQuery))
And here is the same result as you have:
/home/xxx/index.js:7
console.log("result " + Object.entries(returnedByQuery))
^
TypeError: Cannot convert object to primitive value
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at Object.<anonymous> (/home/xxx/index.js:7:23)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
When you performing concatenation, it will try to convert each entry - [key, value] tuple to string, for this it will try to convert given value to string, and here it will fail.
And finally, if you need to get promises from callback based methods:
const p = new Promise(
(res, rej) => connection.query(sql,
(err, result) => {
if (err) return rej(err)
return res(result)
}
)
)
// then you can await it(In async functions)
await p
This is my code 👇
const mongoose = require("mongoose");
mongoose.connect("mongodb:://localhost:27017/crudwithnode", {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log("MongoDB Connected..."))
.catch((err) => console.log(err));
And this is the error I got 👇
MongoParseError: Invalid connection string
at parseConnectionString (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\core\uri_parser.js:547:21)
at connect (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\operations\connect.js:272:3)
at D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\mongo_client.js:215:5
at maybePromise (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\utils.js:719:3)
at MongoClient.connect (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongodb\lib\mongo_client.js:211:10)
at D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongoose\lib\connection.js:709:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongoose\lib\connection.js:706:19)
at Mongoose.connect (D:\Leraning Projects\Mongodb-with-nodeJs\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (D:\Leraning Projects\Mongodb-with-nodeJs\index.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
name: 'MongoParseError',
[Symbol(mongoErrorContextSymbol)]: {}
}
I just tried to run the file using
node "./index.js"
Can I have an solution?
Screen shot 1
Your URL string is not a valid string.
There is a standard structure of URLs i.e.
scheme://host:port/path?query-string#fragment-id
So for making any valid request to some resource, you have to follow the rule. Update your code accordingly.
As the error message already states, you connection string is invalid. I suspect this is because you have two colons after the protocol part (mongodb) in your connection string:
mongodb:://localhost:27017/crudwithnode sould be rather mongodb://localhost:27017/crudwithnode.
Check your connection String.You have two ':' after mongodb whereas it has to be only once.
mongoose.connect('mongodb://localhost/myapp');
You can find better string structuring details at
Mongodb connection String Spec
I am making an App with electron and in the main process, i make an xml parser using child process with the following code:
xmlparser.js
const {parseString} = require('xml2js')
const moment = require('moment')
const testStrangeLayer = new RegExp(/^\de-\d$/)
const parseXML = function(str) {
try {
parseString(
//parse function goes here
)
} catch(e) {
process.exit(3)
}
}
process.on('message',parseXML)
and it is consumed with this:
consumer.js
const fork = require('child_process').fork
const proc = fork('xmlparser.js')
let result
proc.on('message',function(m){
result = m
console.log('parse successful')
proc.kill()
})
proc.on('exit',function(code,signal){
if(code) {
console.error('parsing error')
} else {
console.log(result)
}
})
proc.send(data)
When i am on development stage, this works just fine. The problem comes after i compile the app. And here's the error i found:
Error: Cannot find module 'xml2js'
at Function.Module._resolveFilename (module.js:543:15)
at Function.Module._load (module.js:473:25)
at Module.require (module.js:586:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (C:\<Path to App Folder>\resources\other-scripts\app\xmlp
arser.js:1:178)
at Object.<anonymous> (C:\<Path to App Folder>\resources\other-scripts\app\xmlp
arser.js:53:3)
at Module._compile (module.js:642:30)
at Object.Module._extensions..js (module.js:653:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:504:12)
parsing error
(node:10888) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): #<Object>
(node:10888) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejection
s that are not handled will terminate the Node.js process with a non-zero exit code.
module.js:545
throw err;
^
I wonder what went wrong, i even already add 'child_process' to the project's dependency list. And my aim is to distribute this app without client installing nodejs on their machine.
Thanks for your helps
I have created a mongodb replica set in 3 virtualbox vms, manasger1, worker1, worker2. each replica set has it's own containers. The replica set works fine and I can login to the servers:
docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase "admin"'
MongoDB shell version v3.6.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.4
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
rs1:PRIMARY> use medmart_db
switched to db medmart_db
rs1:PRIMARY> db.providers.findObe()
2018-05-14T17:46:38.844+0000 E QUERY [thread1] TypeError: db.providers.findObe is not a function :
#(shell):1:1
rs1:PRIMARY> db.providers.findOne()
{
"_id" : ObjectId("56ddb50c230e405eafaf7781"),
"provider_id" : 6829973073,
When I run my nodejs application it connects to the replica set. The problem is that when I create a container for my application I get the following exception, my container stops, and I can no longer connect to the replica set PRIMARY, but instead to the secondary.
(node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [worker2:27017] on first connect [MongoNetworkError: connection 5 to worker2:27017 timed out]
at Pool.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:505:11)
at Pool.emit (events.js:182:13)
at Connection.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:329:12)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Socket.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:256:10)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at Socket._onTimeout (net.js:447:8)
at ontimeout (timers.js:427:11)
at tryOnTimeout (timers.js:289:5)
at listOnTimeout (timers.js:252:5)
at Timer.processTimers (timers.js:212:10)
(node:16) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I opened an issue ticket with mongoose for help but their solution doesn't work (they asked that I change from ip address to domain name but I still get the same error).
My connection module is:
'use strict';
const mongoose = require('mongoose');
const getURL = (options) => {
const url = options.servers.reduce((accumulator, current) => {
accumulator += current+',';
return accumulator;
},`mongodb://${options.user}:${options.pass}#`);
return `${url.substr(0,url.length-1)}/${options.db}?replicaSet=${options.repl}&authSource=admin`;
}
const connect = (config, mediator) => {
mediator.once('boot.ready', () => {
const options = {
native_parser: true,
poolSize: 5,
user: config.user,
pass: config.pass,
promiseLibrary: global.Promise,
autoIndex: false,
reconnectTries: 30,
reconnectInterval: 500,
bufferMaxEntries: 0,
connectWithNoPrimary: true ,
readPreference: 'ReadPreference.SECONDARY_PREFERRED',
};
mongoose.connect(getURL(config), options);
mongoose.connection.on('error', (err) => {
mediator.emit('db.error', err);
});
mongoose.connection.on('connected', () => {
mediator.emit('db.ready', mongoose);
});
});
};
module.exports = Object.assign({},{connect});
My config file is:
'use strict';
const serverConfig = {
port: 3000,
};
const dbConfig = {
db: 'xxxxxxx',
user: 'xxxxxx',
pass: 'xxxxxxx',
repl: 'rs1',
servers: (process.env.DB_SERVERS) ? process.env.DB_SERVERS.split(' ') : ['192.168.99.100:27017','192.168.99.101:27017','192.168.99.102:27017'],
};
module.exports = Object.assign({},{dbConfig, serverConfig});
So there are a couple of steps to resolving this issue. First and foremost is the fact that hosts file on the virtualBox machines must be updated to have the ip addresses of mongodb domains. To do that:
> docker-machine ssh manager1
docker#manager1:~$ sudo vi /etc/hosts
#add the following
192.168.99.100 manager1
192.168.99.101 worker1
192.168.99.102 worker2
Repeat for worker1 and worker2.
If by adding the following you are good, then skip the second part.
Next, if you get the following error:
Error: ERROR::providers-service::model::ProviderModel::getProviderById: TypeError: Cannot read property 'wireProtocolHandler' of null
at cb (/home/nupp/app/src/model/ProviderModel.js:182:13)
at /home/nupp/app/node_modules/mongoose/lib/model.js:4161:16
at Immediate.Query.base.findOne.call (/home/nupp/app/node_modules/mongoose/lib/query.js:1529:14)
at Immediate.<anonymous> (/home/nupp/app/node_modules/mquery/lib/utils.js:119:16)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)
Remove any options to mongoose.connect. Here's how mine looks now:
mediator.once('boot.ready', () => {
const options = {};
mongoose.connect(getURL(config), options);
mongoose.connection.on('error', (err) => {
mediator.emit('db.error', err);
});
mongoose.connection.on('connected', () => {
mediator.emit('db.ready', mongoose);
});
});
Hope my solution can help someone else. Took me a few long days to finally figure this out.