我将如何使用 Mongoose 高效地查询 MongoDB?

How would I go about querying MongoDB efficiently using Mongoose?

我正在尝试使用文本查询 MongoDB。

假设我输入“Oven”,服务器应该找到所有的设备和用户,包括设备名为“title”的字段中的单词“Oven”和用户名为“username”的字段。

现在,我的代码如下所示:

const foundContraptions = await Contraptions.find({});
const foundUsers = await Profiles.find({});

const filteredContraptions = QueryContraptions(foundContraptions, query);
const filteredUsers = QueryUsers(foundUsers, query);

function QueryContraptions(arr, query) {
    const filtered = [];
    for (let i = 0; i < arr.length; i++) {
        const contraption = arr[i];
        if (contraption.title.toLowerCase().includes(query.toLowerCase())) {
            filtered.push(removeFile(contraption));
        }
    }
    return filtered;
}

function QueryUsers(arr, query) {
    const filtered = [];
    for (let i = 0; i < arr.length; i++) {
        const user = arr[i];
        if (user.username.toLowerCase().includes(query.toLowerCase())) {
            filtered.push(removeToken(user));
        }
    }
    return filtered;
}

这工作得很好,但假设我的数据库中有 lot 数据,在某些时候我会得到一个错误 HeapOutOfMemory,或者需要很长时间才能执行循环。 所以我想问一下如何使用 Mongoose 高效地查询 MongoDB。

我设法使用 MongoDB 查询运算符自己找到了答案

const contraption = await Contraptions.find({ 'title': { '$eq': query } }).catch(err => { console.log(err); });

https://docs.mongodb.com/manual/reference/operator/query/