【问题标题】:How would I go about querying MongoDB efficiently using Mongoose?我将如何使用 Mongoose 有效地查询 MongoDB?
【发布时间】:2022-01-05 15:06:01
【问题描述】:

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

假设我输入“Oven”,服务器应该找到所有的装置和用户,包括“装置”的“标题”字段中的“Oven”一词和用户的“用户名”字段。

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

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

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

【问题讨论】:

    标签: node.js mongodb mongoose filtering


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 2014-10-10
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多