首页 > 解决方案 > 什么是相当于 Mongoose 填充的 NodeJS mongoDB 客户端?

问题描述

我正在尝试从使用 Mongoose 切换到使用 MongoDB 驱动程序 for JavaScript。在我的一些文件中,我与其他人有关系。我想知道如何“填充”这些。使用 Mongoose,我可以执行以下操作:

Collections.find().populate("field")

我想知道如何使用 MongoDB 驱动程序进行等效操作。有这样做的功能吗?或者,理想情况下,也许可以通过某种方式在聚合管道中做到这一点?谢谢你的帮助。

标签: node.jsmongodbmongoose

解决方案


是的。你能行的。

您可以创建一个函数:

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

然后您还添加一个仅用于在同一文件中收集的功能

希望这对你有用。

亲切的问候


推荐阅读