2016-09-13 100 views
1

我在Node工作區的server.js文件中有以下一段代碼。我的問題是,每次我從bash命令行運行我的server.js文件,我是否設置了一個名爲polls的新集合?或者,MongoDb是否認識到集合已經存在?當我終止與Mongo的連接然後從命令行重新啓動它時呢?下面的代碼中db.createCollection會不會建立一個新的數據庫?

mongo.connect('mongodb://localhost:27017/url-shortener', function(err, newDb){ 
    if(err){ 
     throw new Error('Database failed to connect'); 
    }else{ 
     console.log('Successfully connected to MongoDb database'); 
    } 
    db = newDb; 
    db.createCollection('polls', { 
     autoIndexId: true 
    }); 
}); 
+1

你已經在第一行定義的數據庫路徑指MongoDB的驅動程序的NodeJS文檔。 ˛'db.createCollection'不能創建新的數據庫 – corry

回答

2

db.createCollection有一個名爲strict的選項,默認爲false當設置爲true如果集合已經存在,將返回一個錯誤的對象。修改現有代碼以檢查名稱爲polls的集合是否存在,如果該集合已存在,則拋出錯誤。 `網址shortener`:

mongo.connect('mongodb://localhost:27017/url-shortener', function(err, newDb){ 
    if(err){ 
     throw new Error('Database failed to connect'); 
    } else{ 
     console.log('Successfully connected to MongoDb database'); 
    } 
    db = newDb; 
    db.createCollection('polls', { 
     autoIndexId: true, 
     strict: true 
    }, function(err, collection) { 
     if(err) { 
     //handle error case 
     } 
    }); 
}); 

有關更多信息,你可以在this鏈接

相關問題