Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect mongodb(mongoose) with username and password?

I have username and password for mongoose, i used this url to connect the mongodb using mongoose

I try this one :

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://adminuser:123456@localhost:2017/mydb');

mongoose schema is

  // grab the things we need
  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;

  // create a schema
  var userSchema = new Schema({
  name: String,
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  admin: Boolean,
  location: String,
  meta: {
  age: Number,
  website: String
  },
  created_at: Date,
  updated_at: Date
  });

  // the schema is useless so far
  // we need to create a model using it
  var User = mongoose.model('User', userSchema);

  // make this available to our users in our Node applications
  module.exports = User;

and my controller is

    router.post('/signup',function(req,res){
     console.log("Inside")
     var useR= new User({
      name: 'Chris',
      username: 'sevilayha',
      password: 'password' 
     });
     useR.save(function(err) {
      if (err) throw err;
      console.log('User saved successfully!');
     });
    });

but its not stored in database .

like image 374
parithi info Avatar asked Mar 07 '23 12:03

parithi info


2 Answers

First check whether it connected or node using on event.

mongoose.connect('mongodb://adminuser:123456@localhost:2017/mydb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
});

exports.test = function(req,res) {
  console.log(res)
};
like image 127
Sultan Khan Avatar answered Mar 27 '23 13:03

Sultan Khan


Few years later, updating the new connect code here with additional options -

mongoose.connect(
  'mongodb://user:pass@myhost:27017/my-db?authSource=admin',
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  },
  (err) => {
    if (err) {
      console.error('FAILED TO CONNECT TO MONGODB');
      console.error(err);
    } else {
      console.log('CONNECTED TO MONGODB');
      app.listen(80);
    }
  }
);
like image 30
Bharat Avatar answered Mar 27 '23 13:03

Bharat