首页 > 解决方案 > 有没有办法在仍然使用 mongoose 进行模式定义的同时访问 mongodb node.js 驱动程序功能?

问题描述

我真正想做的是根据文档的属性值为文档的过滤和字符串匹配创建索引。

我知道 mongodb 已经内置了诸如 $text 之类的运算符,它们对这种功能非常有帮助。

我不确定在使用 mongoose 时如何访问这些运算符,或者是否需要使用任何方法来访问它们。

我想使用 mongoose 仍然定义模式和模型,但需要本机 mongodb 的功能。

这可能吗?

标签: node.jsmongodbexpressmongoose

解决方案


以下是我的观点,如果我遗漏了什么或者需要修改或解释清楚,请补充:

1.  You will still be able to use mongoDB's native functionalities on using Mongoose models.
2.  Mongoose is a kind of wrapper on top of native mongoDB-driver.
3.  It would be very useful if you want to have schema based collections/data.
4.  Additionally it would provide few more features than native mongoDB's driver. You might see few syntax differences between those two.
5.  Few examples like `.findByIdAndUpdate()` & `.populate()` are mongoose specific, which has equivalent functionalities available in mongoDB driver/mongoDB as well.  
6.  In general it's quiet common to define mongoose models and use those over mongoDB's functionality in coding(As in node.js - You would write all of your same DB queries on Mongoose models, queries that you execute in DB).

第 2 点:

Mongoose 是位于 Node 的 MongoDB 驱动程序之上的对象文档建模 (ODM) 层。如果您来自 SQL,它类似于关系数据库的 ORM。

第 3 点:

在代码中,如果您使用猫鼬模型来实现您的写入查询,除非您在模型中定义一个字段 - 尽管您在请求中传递它,但它不会被添加到数据库中。此外,您可以执行多项操作,例如使字段唯一/必需等。它使您的 mongoDB 数据看起来像基于模式。如果您的集合数据更像是随机数据(新闻提要类型的东西,其中每个文档的字段不同并且您无法预测数据),那么您可能不关心使用猫鼬。

第 6 点:

假设您使用 mongo shell 或 mongo compass/robo3T 之类的客户端并执行如下查询:

    db.getCollection('yourCollection').find(
    {
        $text: {
            $search: 'employeeName',
            $diacriticSensitive: false
        },
        country: 'usa'
    },
    {
        employee_id: 1,
        name: 1
    }
).sort({ score: { $meta: 'textScore' } });

你会在猫鼬模型上做同样的事情(因为你的CollectionModel已经定义了):

yourCollectionModel.find(
    {
        $text: {
            $search: 'employeeName',
            $diacriticSensitive: false
        },
        country: 'usa'
    },
    {
        employee_id: 1,
        name: 1
    }
).sort({ score: { $meta: 'textScore' } });

在使用 mongoose 时,您会在写入而不是读取方面看到更多的关键功能差异,尽管以上所有内容都与性能无关 - 如果您问我,我可以说您可能会看到使用 mongoose 的性能提升很多。

参考:Mongoose 与 MongoDB 驱动程序


推荐阅读