YDN-DB How to verify if a record exists?

╄→尐↘猪︶ㄣ 提交于 2020-01-05 09:05:26

问题


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

I'd really appreciate your help Thanks!.


回答1:


Your solution is almost correct.

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

  }
}); 

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.

EDIT:

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
      });
    }
  }); 
};

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);
});


来源:https://stackoverflow.com/questions/19203164/ydn-db-how-to-verify-if-a-record-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!