您可以使用本地MongoDb驅動程序創建一個空集合。
var MongoClient = require('mongodb')。MongoClient;
MongoClient.connect('mongodb://localhost:27017/dbName', function(err, db) {
db.createCollection(collectionName, function(err, collection) {
db.close();
})
})
現在,您可以進一步檢查該集合是否存在。如果它不跳過創建或者創建一個。
MongoClient.connect('mongodb://localhost:27017/dbName', function(err, db) {
db.listCollections().toArray(function(err, collections) {
var collectionExists = false;
console.log(JSON.stringify(err,null,1));
if(!err && collections && collections.length>0){
_.each(collections,function (co) {
console.log(JSON.stringify(co.name,null,1));
if(co.name == collectionName){
collectionExists = true;
}
})
}
if(!collectionExists){
db.createCollection(collectionName, function(err, collection) {
})
}
db.close();
});
})
參考文獻:
- http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#listCollections
- http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createCollection
可否請你展示一些代碼,所以我們可以看到你已經嘗試過? – michaelpri
var data = db.model('name','mymodel',「collectionName」), newCollection = new data({}); newCollection .save(function(err){});當使用新數據({})時,使用包含_id的一個文檔字段創建新集合。如何創建空集合? – Nandhini
你可以編輯它到你的問題? – michaelpri