node.js - 什么是相当于 Mongoose 填充的 NodeJS mongoDB 客户端?
问题描述
我正在尝试从使用 Mongoose 切换到使用 MongoDB 驱动程序 for JavaScript。在我的一些文件中,我与其他人有关系。我想知道如何“填充”这些。使用 Mongoose,我可以执行以下操作:
Collections.find().populate("field")
我想知道如何使用 MongoDB 驱动程序进行等效操作。有这样做的功能吗?或者,理想情况下,也许可以通过某种方式在聚合管道中做到这一点?谢谢你的帮助。
解决方案
是的。你能行的。
您可以创建一个函数:
exports.joinRetailCollection = (collectionName, collectionJoinName, foreignFieldName, asFieldName) => state.db.collection(collectionName).aggregate([
{
$lookup:
{
from: collectionName,
localField: collectionJoinName,
foreignField: foreignFieldName,
as: asFieldName
}
}
]);
from: 'user',
localField: 'products',
foreignField: 'sku',
as: 'inventory'
并将其导入
enter code here
const {db} = 要求('../route');
并创建一个变量
const userLink = db.joinRetailCollection('user', .....) //函数的参数。
将此添加到您的 mongo-connector.js 文件中
const MongoClient = require('mongodb').MongoClient
const state = {
db: null,
}
exports.connect = async (url, done) => {
if (state.db) return done()
MongoClient.connect(url, {
connectTimeoutMS: 200,
retryWrites: true,
useNewUrlParser: true,
useUnifiedTopology: true }, (err, client) => {
if (err) return done(err)
state.db = client.db('wp_test')
done()
})
}`
exports.getCollection = (collectionName) => state.db.collection(collectionName);
然后您还添加一个仅用于在同一文件中收集的功能
希望这对你有用。
亲切的问候
推荐阅读
- ms-word - 如何使用 Office JS 启用/禁用 Ms-Word 命令按钮?
- php - laravel递归在父级中添加量
- python - Pyspark-object 没有属性'spark'
- javascript - CSS 在本地显示,但不在 dockerized 服务器上
- angular - 如何使用 bazel 构建 Angular 7 项目
- python-3.x - 为什么不能在我的 python3 结果中将 str 连接到字节
- angular - 无法解析“ngx-cookie-service/lib/cookie.service”
- algorithm - 给定二维空间中的一组点,每个点都有一些惩罚,找到一个正好覆盖 N 个点的凸区域,最小化惩罚
- c# - Unity3D:通过 C# 脚本从 FBX 中提取纹理
- android - 删除自动文本大小android的底部空间