node.js - 有没有办法在仍然使用 mongoose 进行模式定义的同时访问 mongodb node.js 驱动程序功能?
问题描述
我真正想做的是根据文档的属性值为文档的过滤和字符串匹配创建索引。
我知道 mongodb 已经内置了诸如 $text 之类的运算符,它们对这种功能非常有帮助。
我不确定在使用 mongoose 时如何访问这些运算符,或者是否需要使用任何方法来访问它们。
我想使用 mongoose 仍然定义模式和模型,但需要本机 mongodb 的功能。
这可能吗?
解决方案
以下是我的观点,如果我遗漏了什么或者需要修改或解释清楚,请补充:
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 的性能提升很多。
推荐阅读
- php - WCFM 多供应商市场+ Woocommerce 返回商店/继续购物到单一供应商商店
- xml - 如何使用 XSLT 1.0 对 xml 的多个嵌套元素组进行排序?
- r - 如何将ggplot中x轴的原点从“八月到三月”而不是“一月到三月,八月到十二月”?
- apache-spark - 通过 JDBC 在受限环境中通过流式处理或批处理处理整个 SQL 表
- swift - 链接框架“Pods_Lebsi.framework”缺少此目标所需的一个或多个架构:x86_64 - Xcode
- indexing - 为 xarray 中的每个纬度/经度点选择给定日期的值
- r - R中有没有办法找到这个图的回归线,然后也使用ggplot2显示方程?当前方法似乎不正确
- javascript - 如何在 ReactJS 中嵌套 3 个 map 循环函数
- android - 如何在 Jetpack Compose 上更改 TextField 突出显示的文本颜色?
- javascript - 如何从待办事项列表中切换项目