如何使用用户名和密码连接mongodb(mongoose)?

12

我有mongoose的用户名和密码,我使用这个url连接mongodb使用mongoose:

我尝试了这个:

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

mongoose模式是什么?

  // 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;

我的控制器是

    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!');
     });
    });

但这并没有存储在数据库中。


1
我也使用了 createConnection()。 - parithi info
1
mongodb://adminuser:123456@localhost:2017/mydb' i think port is wrong, should be 27017 mongodb://adminuser:123456@localhost:27017/mydb' - Subburaj
2个回答

11

首先检查它是否连接或节点使用 on 事件。

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)
};

8
几年后,更新了新的连接代码,并增加了其他选项 -
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);
    }
  }
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接