Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 创建具有索引的集合_Javascript_Mongodb - Fatal编程技术网

Javascript 创建具有索引的集合

Javascript 创建具有索引的集合,javascript,mongodb,Javascript,Mongodb,我想创建一个具有唯一索引的集合。 我曾经认为在我的应用程序启动中这样做就足够了- db.collection('myCollection', {strict: true}, function (err, collection) { if (!err) { collection.ensureIndex({ "name" : 1},{unique: true}, function dummy(result,err){}); } }); `` 但是,当应用程序

我想创建一个具有唯一索引的集合。 我曾经认为在我的应用程序启动中这样做就足够了-

db.collection('myCollection', {strict: true}, function (err, collection) {
    if (!err)
    {
        collection.ensureIndex({ "name" : 1},{unique: true}, function dummy(result,err){});
    }
});
``

但是,当应用程序第一次运行时,“myCollection”集合不存在,因此不会调用我的“ensureIndex”。回调将返回错误。这意味着我的索引没有按预期创建

我看到您可以使用createCollection函数,但据我所知,这不是标准做法。 在插入第一个文档时,确保我的索引已经就位的最佳做法是什么?

从调用中删除{strict:true}选项;这就是导致它在集合不存在的情况下向回调返回错误的原因,这是该选项的唯一目的

db.collection('myCollection', function (err, collection) {
    if (!err)
    {
        collection.ensureIndex({"name": 1},
                               {unique: true}, 
                               function dummy(result,err){});
    }
});