我正在尝试使用系统中的 Mongoose 连接到 mLab,但它始终失败并出现以下错误
name: 'MongoError',
message: 'failed to connect to server [server address here] on first connect' }
这是我的代码:
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var options = {
server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } }
};
mongoose.connect('mongodb://username:password@server.mlab.com:port/appname', options);
var conn = mongoose.connection
conn.on('error', console.error.bind(console, 'connection error:'));
var User = mongoose.model('User', new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean,
location: String,
created_at: Date,
updated_at: Date
}));
var new_user = new User({
name: 'name',
username: 'username',
password: 'password'
});
conn.once('open', function() {
console.log('started')
new_user.save(function(err) {
if (err) throw err;
console.log('User created!');
});
});
请告诉我如何成功连接到 mLab。
最佳答案
我刚才也遇到了同样的问题。就我而言,我通过 VPN 连接到我的办公室网络,但它被阻止了。
解决方案:- 我断开与 VPN 的连接并运行命令进行连接,并且能够连接。 希望对您有帮助!
关于node.js - Mongoose 连接 mLab 时出现连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40780131/