如何找出为什么MongoDB NodeJS驱动程序不返回单个集合的有效查询结果?



我正在使用MongoDB v3.2.7 for NodeJS v10.16.0。 我创建了一个MongoRepository基类,我们已经在生产中使用了几年。 有时在开发中,我发现一些古怪的行为,它不会返回特定集合的任何结果。 我曾经认为这是因为我没有在查询之间关闭客户端。 我现在不太确定。

我正在通过Express服务器运行代码,其他六个调用工作正常。 然后我得到这个查询和投影,没有结果(即使这些在命令行和 Robo 3T 中工作(:

查询 = {"pin":"xxxxxx","documentId":"5c584a76a690bb28ff8021cb","page":1}, 投影 = {"_class":0,"documentId":0,"pin":0,"base64":0} data = []

我不知道如何开始调试它。 帮助?

下面是基类代码:

import { MongoClient, ObjectId } from 'mongodb';
import 'dotenv/config';
const url = process.env...; // elided to hide our secrets
const dbname = process.env...; // elided to hide our secrets
class MongoRepository
{
/**
* Returns the database using the configuration
*/
async getDatabase()
{
if (!MongoRepository.client)
{
MongoRepository.client = new MongoClient(url, { useNewUrlParser: true });
await MongoRepository.client.connect();
if (!MongoRepository.client || !MongoRepository.client.db(dbname))
{
throw new Error(`Unable to connect to Mongo with URL '${url}'`);
}
}
return MongoRepository.client.db(dbname);
}
/**
* Override this method in children to add any special query filter for a collection.
* @param {*} query query object to modify
*/
addRepositoryFilter(query) {
return query;
}
/**
* Generic find method that takes a query and a projection.
*
* @param {*} query Lookup parameters
* @param {*} projection Fields to return or not return from the search
*
*/
async find(query, projection = {})
{
query = this.addRepositoryFilter(query);
let db = await this.getDatabase();
return await db.collection(this.CollectionName).find(query).project(projection).toArray();
}
}
export default MongoRepository;

下面是未获得结果的子类:

import MongoRepository from "./MongoRepository";
class ViewerPageRepository extends MongoRepository
{
get CollectionName()
{
return 'viewerPage';
}
async findByPinDocumentIdPage(pin, documentId, page, projection)
{
documentId = this.objectIdToString(documentId);
let query = {
pin: pin,
documentId: documentId,
page: page
};
console.log(`Query = ${JSON.stringify(query)}, Projection = ${JSON.stringify(projection)}`);
return await this.find(query, projection);
}
}
export default ViewerPageRepository;

我在考虑检查查询中的documentId类型后想通了这一点。 它作为十六进制字符串存储在我正在查询的集合中。 我没有在我的代码中包含objectIdToString函数,但如果它是ObjectId实例,它会在documentId上调用valueOf。 这应该将其转换为字符串,但由于某种原因,我正在返回另一个ObjectId实例(也许是我调用valueOf的同一实例 - 我没有检查(。 因此,这似乎是由MongoDB驱动程序的ObjectId::valueOf方法中的错误引起的。 我会报告这个问题。

最新更新