【问题标题】:talking to PouchDB Basics与 PouchDB 基础知识交谈
【发布时间】:2015-01-29 12:38:27
【问题描述】:

也许这是一个绝对愚蠢的问题,但我有一个看起来像这样的 Pouchdb 数据库:

var fragDB = {
        _id: new Date().toISOString(),
        question: quest,
        right: right,
        wrong1: wrong1,
        wrong2: wrong2,
        wrong3: wrong3,
        source1: source1,
        source2: source2,
        tags: tagarr
    }

    db.put(fragDB);

现在我想从最后一个文档中检索标签作为数组。我尝试了类似的方法,但这显然不起作用。

var alltags = function(){

    db.allDocs({include_docs: true, limit: 1, descending: true}, function(err, response){
        if (err) {
            console.log(err);
            console.log("loading Standard Tags");
            return ["..."];
        }
        if (response){
            console.log(response.tags);
            return response.tags;
        }
    });
};

我错过了什么?

【问题讨论】:

    标签: javascript pouchdb


    【解决方案1】:

    这不是一个愚蠢的问题——它很难理解,因为 PouchDB 是异步的:http://pouchdb.com/guides/async-code.html

    在您的代码中,函数中有一个函数,它是返回response.tags子函数,而不是父函数。

    我建议你阅读上面的链接,这样你就可以学习如何编写 promisey 异步代码,例如:

    db.allDocs({
      include_docs: true, 
      limit: 1, 
      descending: true
    }).then(function (response) {
      console.log(response.tags);
      return response.tags;
    }).catch(function (err) {
      console.log(err);
      console.log("loading Standard Tags");
      return ["..."];
    }).then(function (tags) {
      // do something with the tags
    });
    

    【讨论】:

    • 我不知道,如果这真的是问题所在,将“console.log(response.tags)”设置为“console.log(response)”也会在您的正如我的建议。对我来说,语法似乎是错误的,因为我无法正确访问此文档。
    • 哦,对了,对不起。您的response 对象实际上包含文档列表,所以它应该是response.rows[0].tags
    • 其实是response.rows[0].doc.tags,我才一秒就发现了。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 2018-05-25
    • 2014-11-28
    • 2014-02-14
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多