gpt4 book ai didi

node.js - 有没有办法访问 mongodb node.js 驱动程序功能,同时仍然使用 mongoose 进行模式定义?

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:39 24 4
gpt4 key购买 nike

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

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

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

我想使用 mongoose 仍然定义架构和模型,但需要 native 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 是一个对象文档建模 (ODM) 层,位于 Node 的 MongoDB 驱动程序之上。如果您来自 SQL,它类似于关系数据库的 ORM。

第三点:

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

第 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' } });

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

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

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

引用号:Mongoose Vs MongoDB Driver

关于node.js - 有没有办法访问 mongodb node.js 驱动程序功能,同时仍然使用 mongoose 进行模式定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57618952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com