mongoose connection error always - mongodb

whenerver i try to connect mongodb using mongoose following error occurred.
{ db: { native_parser: true },
server: { poolSize: 5 },
user: '',
pass: '' }
+++++++++++++++++++++++ SERVER STARTED +++++++++++++++++++++++++++ Server running at:http://127.0.0.1:5000 DB Error jobs: { [MongoError:
auth failed] name: 'MongoError', message: 'auth failed', ok: 0,
errmsg: 'auth failed', code: 18 } var option = { db: { native_parser:
true }, server: { poolSize: 5 }, user:db.username, pass:db.password, }
mongoose.connect(option, option, function(err) {if (err) { process.exit(1); } else { console.log('MongoDB Connected', mongoUrl);
} })

Related

How to build a register live api successfully on heroku?

How to fix this, mongo error MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.
const db = require('./configs/config').get(process.env.NODE_ENV);
my code is:
index.js
mongoose.Promise = global.Promise;
mongoose.connect(db.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true }, function (err) {
if (err) console.log(err);
console.log("database is connected");
})
config.js code:
const config = {
production: {
SECRET: process.env.SECRET,
DATABASE: process.env.MONGODB_URI
},
default: {
SECRET: 'mysecretkey',
// DATABASE: 'mongodb://localhost:27017/eduInternJan'
DATABASE: 'mongodb+srv://Sagarkumar:Sagar457#cluster0.96hmj.mongodb.net/loginapi?retryWrites=true&w=majority'
}
}
exports.get = function get(env) {
return config[env] || config.default
}

Can make post request to localhost using node-fetch, but unable to do so using Axios

I have tried making the same post request using node-fetch and axios.
var fetch = require('node-fetch');
var axios = require('axios');
async function fetchTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const streamResponse = await fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
const jsonResponse = await streamResponse.json()
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function axiosTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const jsonResponse = await axios({
method: 'post',
url: `${host}:${port}`,
data: body
})
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function test() {
console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
}
test();
The request made with node-fetch works nicely. The request made with axios returns (IP address redacted with ...) an error:
{ successMessage: '',
errorMessage:
{ Error: connect ECONNREFUSED ...:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '...',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'http://127.0.0.1:8801',
data: '{"type":"request","cmd":"devices"}' },
request:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 39,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://.../',
_isRedirect: true },
response: undefined } }
What might be the reason? Am I doing something wrong?
EDITED with more info requested in comment:
The axios request fails the same way if I comment out the node-fetch request.
The node-fetch request returns:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response' },
}
Since I wrap the result in a response object, the console.log looks like
{
successMessage:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response'
},
errorMessage: ''
}

hapi : Cannot start server before plugins finished registration

I am getting error on initial setup with Hapi and MongoDB and I am getting error after starting my server.
Code:
const Hapi = require('hapi');
var Boom = require("boom");
const dbOptions = {
url: "mongodb://localhost:27017/comparekaro",
settings: {
db: {
native_parser: false
}
}
}
const server = new Hapi.Server();
server.connection({
port : 3001,
router : {
stripTrailingSlash : true,
},
routes : {
cors : true,
}
});
server.route({
method: 'GET',
path: '/',
handler: (request, reply) => {
var db = request.server.plugins['hapi-mongodb'].db;
var ObjectID = request.server.plugins['hapi-mongodb'].ObjectID;
db.collection('catalogs').find((err, result) => {
if (err) return reply(Boom.internal('Internal MongoDB error', err));
reply(result);
});
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: (request, reply) => {
reply(`i am ${request.params.name}`);
}
});
server.register({
register: require('hapi-mongodb'),
options: dbOptions
}, function (err) {
if (err) {
console.error(err);
throw err;
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
Move server.start callback inside the server.register callback, these are async operations that need to be run in a logical order.

Sails.js: cannot do POST for inserting into mongoDB

I am trying to write a toy program for submitting form and inserting into mongodb, but I keep getting DB error. Let me paste the relevant code here, and I hope to get some help.
I am using Sails ver 0.10.5 and the latest mongo 2.6.5, and my I run node on my Mac OSX 10.9:
Model: Employee.js
module.exports = {
attributes: {
name: {
type: "string",
required: true
},
email: {
type: "string",
required: true
},
password: {
type: "string",
required: true
}
},
beforeCreate: function(values, next) {
next();
}
};
route.js:
module.exports.routes = {
'/registeremployee': {
controller: 'employee',
action: 'register'
},
'/listemployees': {
controller: 'employee',
action: 'list_all'
}
};
EmployeeController.js
module.exports = {
index: function(req, res) {
res.send(200, {title: "employee index page"});
},
list_all: function(req, res) {
Employee.find().exec(function(err, employee) {
if (err) {
res.send(500, {title: 'error retrieving users'});
} else {
res.send(200, {'employees': employee});
}
});
},
register: function(req, res) {
if (req.method == "GET") {
res.view({title: "Form for registering employees"});
} else if (req.method == "POST") {
var username = req.param("username");
var password = req.param("password");
var email = req.param("email");
console.log("saving the username: " + username); //username printed as 'undefined'
Employee.create({username: username, password: password, email: email}).exec(function(error, employee) {
if (error) {
console.log('error');
res.send(500, {error: "DB error!"});
} else {
console.log('error');
res.send(200, employee);
console.log("saved employee: " + employee.username);
}
});
}
}
};
Lastly, the register.ejs template file:
List All Users
<h2>Form - Create a User</h2>
<form action="/registeremployee" method="POST">
<table>
<tr><td>Name</td><td><input type=”text” name=”username” required></td></tr>
<tr><td>Password</td><td><input type=”password” name=”password” required></td></tr>
<tr><td>Email</td><td><input type=”email” name=”email” required></td></tr>
<tr><td></td><td><input type="submit"></td>
</table>
</form>
It looks to me that the form does not submit data, as the parameters are printed as undefined/null in my controller.
I have this in my connections.js:
mongo: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
user: '',
password: '',
database: 'sailsApp1'
}
just replace name to username and you are able to save data in db.
module.exports = {
attributes: {
username: {
type: "string", required: true },
email: { type: "string", required: true },
password: { type: "string", required: true } },
beforeCreate: function(values, next) { next(); } };

Can't connect to mongodb from mocha test

Connecting from the REPL works fine:
> var mongoose=require('mongoose');
undefined
> mongoose.connect('mongodb://localhost/test', function(error) {
... console.log( 'connected\n%s\n', error );
... });
returns:
{ connections:
[ { base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'test',
options: [Object],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
_events: {},
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: {} }
> connected # Yes!
undefined
But connecting from a Mocha test suite does not work:
var mongoose = require( 'mongoose' );
console.log( 'connecting...' );
mongoose.connect( 'mongodb://localhost/test', function( error ) {
if( error) console.error( 'Error while connecting:\n%\n', error );
console.log( 'connected' );
});
returns:
$ mocha
connecting...
0 passing (0 ms)
Does anyone know why this not working?
Do you have any tests in your suite? If not it seems like mocha exits before mongoose gets a chance to connect. One of the features listed on the mocha page is
auto-exit to prevent "hanging" with an active loop
which may have something to do with it. You could try connecting to mongoose in the before method of your test suite e.g.
describe('test suite', function() {
before(function(done) {
mongoose.connect('mongodb://localhost/test', function(error) {
if (error) console.error('Error while connecting:\n%\n', error);
console.log('connected');
done(error);
});
});
});