通过obj数组的键索引PouchDB数据库

时间:2018-02-01 06:59:06

标签: couchdb pouchdb

我在PouchDB中有类似的数据,大约有200K这样的记录

{
    "title": "blah blah blah",
    "authors": [
        { "name": "Fudd, Elmer"},
        { "name": "Duck, D."},
        { "name": "Walker, Diana"},
        { "name": "Washington, Grg,"}
    ],
    "description": "The annals"
}

我希望能够查询作者

db.find({
    "selector": {
        "authors.name": {
        "$regex": "^Wa"
        }
    },
    "fields": ["_id", "title", "authors"]
}, function (err, result) {
    if (err) { return console.log(err); }

    console.log(result);
});

问题是,我无法弄清楚如何为作者制作索引。我尝试了很多变种,包括

const docsByAuthorName = function(doc) {
    for (let element of doc.creators) {
        emit(element.name, element);
    }
};

let idx = {
    fields: [{
        "name": { "map": docsByCreatorName }
    }],
    ddoc: "authors",
    name: "name",
    type: "json"
};

db.createIndex({
    index: idx
}, function (err, result) {
    if (err) { return console.log(err); }

    console.log(result)
});

但是我继续得到没有索引的消息,我应该索引我的数据库来改进查询时间。我做错了什么?

更新:我在secondary indexes上发现了一条帖子,并按照那里的说明进行了

let idx = {
    _id: '_design/authorsByName',
    views: {
        'authorsByName': {
            map: function(doc) {
                for (let element of doc.creators) {
                    emit(element.name); 
                }
            }
        }
    }
};

db.put(idx).then(function (info) {
    // design doc created
}).catch(function (err) {
     // if err.name === 'conflict', then
     // design doc already exists
});

当我运行查询时,出现以下错误

SyntaxError: Unexpected token for
    … <snip> …
The user's map/reduce function threw an uncaught error.
You can debug this error by doing:
myDatabase.on('error', function (err) { debugger; });
Please double-check your map/reduce function.
evalmachine.<anonymous>:34
};var log = function () {};var isArray = Array.isArray;var toJSON = JSON.parse;var __emitteds__ = [];var emit = function (key, value) {__emitteds__.push([key, value]);};var __result__ = (for (let element of doc.creators) {
                                                                                                                                                                                           ^^^

所以,现在我不确定我是否可以将常规JS放入PouchDB map函数

1 个答案:

答案 0 :(得分:0)

更新地图功能中,进行以下更改:

//for (let element of doc.creators) {
for(var i=0, length=doc.creators.length; i<length; i++){
    //emit(element.name);
    emit(doc.creators[i], doc.title);
}

查看this answerthis one