简体   繁体   English

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

[英]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我有 mongoose 的用户名和密码,我用这个 url 连接 mongodb 使用 Z758D31F351CE141BF20CZ

I try this one:我试试这个:

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

mongoose schema is 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;

and my controller is我的 controller 是

    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.但它没有存储在数据库中。

First check whether it connected or node using on event.首先检查它是否连接或使用 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)
};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM