【问题标题】:How to connect mongodb(mongoose) with username and password?如何使用用户名和密码连接 mongodb(mongoose)?
【发布时间】:2018-05-08 07:06:28
【问题描述】:

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

我试试这个:

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

猫鼬模式是

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

但它没有存储在数据库中。

【问题讨论】:

  • 我也使用了 createConnection()
  • mongodb://adminuser:123456@localhost:2017/mydb' 我觉得端口不对,应该是27017 mongodb://adminuser:123456@localhost:27017/mydb'

标签: node.js mongodb mongoose


【解决方案1】:

首先检查它是否连接或使用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)
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2011-06-20
    • 1970-01-01
    • 2021-12-06
    • 2015-04-11
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多