问题:如何用用户名和密码连接mongodb(mongoose)?

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

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

解答

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

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐