我需要知道db I中是否存在一个对象。我知道我可以使用query.count来测试结果是否为零然后它不存在它存在。但有人告诉我数量很贵,所以我认为查询。第一可能更有效率。这是真的吗?测试db中对象存在的最佳方法是什么?
答案 0 :(得分:0)
查询首先不计算你的结果你可以使用查询查找然后使用array.length测试数组长度如果超过0或不
答案 1 :(得分: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
所以在我的好空,在内存mongo中,它的超快速(那些是毫秒),因此,假设你的查询被很好地索引,选择产生最可读代码的那个;)