我正在尝试使用NodeJS驱动程序在MongoDB中创建一个上限集合。
db.createCollection(req.body.name,options,function onCreateCollection(mongoErr,mongoCollection){
if(mongoErr){
...
}else{
console.log( mongoCollection.collectionName );
...
}
});
集合名称在控制台上打印,但show collections
未列出。我尝试了一个带连字符的名字this-is-a-collection
。
为什么?
另外,命名集合有哪些限制?
答案 0 :(得分:2)
我不知道为什么你的代码不起作用。但我只是尝试用这个简单的脚本创建一个带有带连字符的名称this-is-a-collection
的集合,它起作用了。
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/db';
MongoClient.connect(url, function(err, db) {
console.log("Connected correctly to server");
db.createCollection('this-is-a-collection', { capped : true, size : 10000 } ,function onCreateCollection(err,mongoCollection){
if(err){
console.log(err);
} else {
console.log(mongoCollection.collectionName);
}
db.close();
});
});
在CLI中:
MBP:mongo sapher$ mongo
MongoDB shell version: 3.0.5
connecting to: test
....
> use db
switched to db db
> show collections
system.indexes
this-is-a-collection
您可以按照此link获取有关MongoDB命名限制的更多信息。
对于命名约定,我个人使用像remote_users
这样的蛇案例。我认为这是命名系列的最优雅方式。只要你保持一致,命名并不重要。
答案 1 :(得分:1)
事实证明,在较旧版本的驱动程序1.4.x
上,创建一个没有指定size
选项的上限集合并不会导致错误。 它甚至会返回成功回复。在较新版本2.0.x
上,它确实会导致错误。
对于有上限的集合,size
是可选的,而max
是可选的。 docs稍微含糊不清,因为它们并未声明您需要size
来创建上限集合。