简体   繁体   English

用JavaScript索引一个Mongo数据库

[英]index a mongo db with javascript

I have working script which stores the html forms i have created in mongoDB. 我有一个工作脚本,用于存储在mongoDB中创建的html表单。 It works awesome. 它很棒。 However, i can't search any of the data i place in mongo, because i don't have an index. 但是,我无法搜索放置在mongo中的任何数据,因为我没有索引。

I realize I could create the index from the console, but for my system to work the way we need, I really need the index to be created when the data is stored. 我意识到我可以从控制台创建索引,但是要使我的系统按我们需要的方式工作,我确实需要在存储数据时创建索引。 So, i need to place code in the javascript that actually creates the code 9using node.js or directly). 因此,我需要将代码放置在实际上使用node.js或直接创建代码9的javascript中。

I tried the following javascript (with node.js), but it does not appear to work. 我尝试了以下javascript(使用node.js),但似乎无法正常工作。

app.post('/:db/:collection/formSubmit', function(req, res) {
    var json = form2json.transform(req.rawBody);    
    var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port,mongoOptions ));
        db.open(function(err, db) {
        db.authenticate(config.db.username, config.db.password, function () {
        db.collection(req.params.collection, function(err, collection) {
      collection.insert(Array.isArray(json) ? json[0] : json, function(err, docs) {
    res.header('Content-Type', 'application/json');
    if(req.is('application/xml')) {
    res.send('<ok>1<ok>')
    } else {
    es.send(json, 201);       
    } 
// my attempt to create an index while posting a form follows
    db.core.ensureIndex( { "document": 1 } )    
        db.close();
        });
    });
  });
});

}); });

You need to call ensureIndex on the collection: 您需要在集合上调用ensureIndex

collection.ensureIndex({ "document": 1 }, function (err, indexName) {    
    db.close();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM