我可以连接到localhost或Atlas,但是当我尝试使用||时。坏了连接到Atlas时必须指定“ dbName”,但这会破坏我的本地主机。
此代码适用于localhost:
mongoose.connect( process.env.LOCAL );
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
此代码适用于我的地图集:
mongoose.connect( process.env.ATLAS_URI, { useNewUrlParser: true, dbName: 'wwatlasDB' });
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
但是当我尝试时:
mongoose.connect( process.env.LOCAL || process.env.ATLAS_URI, { useNewUrlParser: true, dbName: 'wwatlasDB' });
失败。有办法吗?
答案 0 :(得分:0)
简单的方法就是检查在env
之前是否有当前的connect
,例如:
if(process.env.LOCAL) {
mongoose.connect( process.env.LOCAL );
} else {
mongoose.connect( process.env.ATLAS_URI, { useNewUrlParser: true, dbName: 'wwatlasDB' } );
}
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
答案 1 :(得分:0)
mongoose.connect( process.env.ATLAS_URI, { useNewUrlParser: true, dbName: 'wwatlasDB' });
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
这似乎也可以在本地连接!