Node.js入门踩坑

341 阅读1分钟

1) 学习node.js连接MongoDB数据库的时候,照着Mongoose中文文档写的这段代码

connect() 返回一个状态待定(pending)的连接, 接着我们加上成功提醒和失败警告。

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

运行的时候报错

DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

Port 3000 is already in use...

以上问题的解决办法:

mongoose连接数据库时除了url参数外增加2个参数,如下所示:

mongoose.connect("mongodb://127.0.0.1:27017/test",{useNewUrlParser:true},function(err){
  if(err){  
    console.log('Connection Error:' + err)  
  }else{   
    console.log('Connection success!')}  
});

2) ejs默认在views目录,不指定默认是这个配置

app.set('views',__dirname+'/views')