【问题标题】:indexing a PouchDB db by the keys of an array of obj通过 obj 数组的键索引 PouchDB 数据库
【发布时间】:2018-02-01 06:59:06
【问题描述】:

我在 PouchDB 中有这样的数据,大约有 20 万条这样的记录

{
    "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 函数中

【问题讨论】:

    标签: couchdb pouchdb


    【解决方案1】:

    在你更新的地图功能中,进行如下修改:

    //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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-23
      • 2018-05-02
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 2015-02-11
      • 2018-12-24
      • 2021-12-01
      相关资源
      最近更新 更多