使用find,count或first in parse来测试是否存在
问题描述:
我需要知道一个对象是否存在于我正在使用的db中。我知道我可以使用query.count来测试结果是否为零,否则它不存在。但有人告诉我,计数很贵,所以我认为query.first可能更有效。这是真的,测试db中对象存在的最好方法是什么?使用find,count或first in parse来测试是否存在
答
查询首先将不计入你的结果,你可以使用查询发现,然后如果使用array.length测试数组的长度大于0或不
答
这将是有益的,如果你表现出一定的代码,但是这是太好玩了一个问题就过去了。
测试代码在下面,但我的非科学答案是:只要查询索引良好,它可能无所谓你使用哪种方法。当你计算大量的对象时,计数是很昂贵的,但如果你只是想找到一个并且查询被索引,我认为它不会很昂贵。
好的,现在有些代码。我在我的parse-server repo中编译了一些单元测试,以测试我能想到的三种测试存在的方式。在所有三种情况下,我使用的可能是特殊的objectId,因此您可以轻松调整它。我也只做了一次每个测试,而要做到科学性,我们想每次做100次,平均每次测试。但是之后我们需要考虑查询缓存,所以我只是保持简单,并且可以使用相同的模式对自己的数据进行真实测试。
好了,现在我已经给了我所有的注意事项:
describe('way to find if an object exists....', function() {
beforeEach(function (done) {
new Parse.Object('Test')
.save()
.then((testObj) => {
this.testObj = testObj;
done();
})
.catch(done.fail);
});
it('should use get if we know object id', function(done) {
this.start = new Date();
new Parse.Query('Test').get(this.testObj.id)
.then(result => {
console.log('get time exists', new Date() - this.start);
return expect(result.id).toBe(this.testObj.id);
})
.then(() => {
this.start = new Date();
return new Parse.Query('Test').get('not the id');
})
.then(
() => done.fail('we shouldn\'t get here, cause the obj doesn\'t exist'),
// so if the get is rejected you know it doesn't exist.
e => {
console.log('get time does not exist', new Date() - this.start);
expect(e).toEqual(new Parse.Error(101, 'Object not found.'));
})
.then(done)
.catch(done.fail);
});
it('should also work with find', function (done) {
this.start = new Date();
new Parse.Query('Test')
.equalTo('objectId', this.testObj.id)
.find()
.then(result => {
console.log('find time exists', new Date() - this.start);
return expect(result.length).toBe(1);
})
.then(() => {
this.start = new Date();
return new Parse.Query('Test')
.equalTo('objectId', 'not the id')
.find();
})
.then((result) => {
console.log('find time does not exist', new Date() - this.start);
expect(result.length).toEqual(0);
})
.then(done)
.catch(done.fail);
});
it('should also work with count', function (done) {
this.start = new Date();
new Parse.Query('Test')
.equalTo('objectId', this.testObj.id)
.count()
.then(result => {
console.log('count time exists', new Date() - this.start);
return expect(result).toBe(1);
})
.then(() => {
this.start = new Date();
return new Parse.Query('Test')
.equalTo('objectId', 'not the id')
.count();
})
.then((result) => {
console.log('count time does not exist', new Date() - this.start);
expect(result).toEqual(0);
})
.then(done)
.catch(done.fail);
});
});
这将产生这样的结果:
Jasmine started
way to find if an object exists....
✓ should use get if we know object id
get time exists 19
get time does not exist 8
✓ should also work with find
find time exists 12
find time does not exist 9
✓ should also work with count
count time exists 7
count time does not exist 6
所以在我的漂亮的空,在内存蒙戈,其所有的超级速度极快(那些是毫秒),所以,假设你的查询索引很好,选择一个产生最可读代码的那个;)
我需要测试存在只有我不需要结果数 –