YDN-DB如何验证,如果记录存在? [英] YDN-DB How to verify if a record exists?

查看:181
本文介绍了YDN-DB如何验证,如果记录存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证一个特定的记录表里面存在一个给定的ID。例如:

I'm trying to verify if a specific record exist inside a table by a given ID. For example:

var id = 23;
db.count('products',id).done(function(count) {
    if(count>0){
        db.get('products',id).done(function(r) {
            //Do something
        });
    }else{
        alert('No product found');
    }
});

当我尝试,我得到了以下错误:未捕获的异常:空

When I try this, I get the following error: uncaught exception: null

我真的AP preciate你的帮助谢谢!

I'd really appreciate your help Thanks!.

推荐答案

您的解决方案几乎是正确的。

Your solution is almost correct.

在IndexedDB的API,没有存在方法,可能是因为它可以使用模拟计数方法。但计数方法只接受重点范围,所以存在测试应该是:

In IndexedDB API, there is no exists method, probably because it can be emulated using count method. But count method accepts only key range, so existence test should be:

var id = 23;
db.count('products', ydn.db.KeyRange.only(id)).done(function(cnt) {
  if (cnt) { // exist

  } else { // no exist

  }
}); 

还有一个原因,存在方法在IndexedDB的API不存在的是, GET 不给错误不存在的关键。所以你可以放心,并建议,要做到:

Another reason, exists method don't exist in the IndexedDB api is that, get don't give error for non-existing key. So you can safely, and recommended, to do:

var id = 23;
db.get('products', id).done(function(product) {
  if (product) { // exist

  } else { // no exist

  }
});

我想指出的是,在这两种方式来检测存在的,因为它避免反序列化的第一个方法是更有效的。所以,如果你只需要测试存在,使用第一种方法。用于检索记录,这可能或可能不存在,则使用第二方法

I would like to point out that, in these two ways to detect existence, the first method is more efficient because it avoid deserialization. So if you just need to test for existence, use first method. For retrieving a record, which may or may not exist, use second method.

编辑:

要查询按主键,标识,或记录唯一辅助键,SKU

To query a record by primary key, id, or unique secondary key, sku

/**
* @param {string} id id or sku
* @param {Function} cb callback to invoke resulting record value. If not exists in the
* database, null or undefined is returned.
*/
var getByIdOrSku = function(id, cb) {
  var req = db.get('items', id);
  req.done(function(item) {
    if (item) {
      cb(item) 
    } else {
      db.values('items', 'SKU', ydn.db.KeyRange.only(id), 1).done(function(items) {
        cb(items[0]); // may not have result
      });
    }
  }); 
};

如果您preFER承诺方式:

If you prefer promise way:

db.get('items', id).then(function(item) {
   if (item) {
      return item;
   } else {
      return db.values('items', 'SKU', ydn.db.KeyRange.only(id), 1).done(function(items) {
          return items[0];
      });
   }
}).done(function(item) {
   // result query as as id or SKU
   console.log(item);
});

这篇关于YDN-DB如何验证,如果记录存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆