【问题标题】:What is the NodeJS mongoDB client equivalent to Mongoose populate?什么是相当于 Mongoose 填充的 NodeJS mongoDB 客户端?
【发布时间】:2021-05-07 02:12:10
【问题描述】:

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

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

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

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

是的,是的。你可以做到的。

你可以创建一个函数:

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} = require('../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);

然后是函数 您还可以在同一文件中添加一个仅用于收集

希望这对你有用。

亲切的问候

【讨论】:

  • 您好,谢谢您的回答。我想我大体上理解你在这里解释的概念。但是,它并不完全清楚。如果您可以仔细检查您的答案并使其更清晰/更笼统,那么我很乐意接受它作为答案。
  • 嘿,当然。我会一步一步地给你写信。就我而言,我使用的是 Apollo,但配置是相同的。所以我有这个文件夹结构。 src --> (db, constants, controllers, graphql, utils, services, 也许是模型。在 db 文件夹中,我有另一个文件夹名称连接器,在其中,我创建了一个 mongo-connector.js,在其中配置 mongodb。通过我在其他评论中附加了您的代码,或者您也可以在第一个答案中阅读它。然后我导入到作为根文件的 index.js 中。阿波罗在上下文中,在整个应用程序中都可以使用。但是这里有我留给你的代码。
  • 点击链接查看示例代码。在这种情况下是阿波罗服务器。但是您可以像我一样访问数据库。希望它对你有用。无论如何,如果不是这种情况,您可以再次回答。亲切的问候。 codesandbox.io/s/heuristic-mountain-7m12t
  • 如何在数组中的对象中填充字段:{list:[{refField:ObjectId, /*other fields */}, ...more objects ]}?我需要这样的等价物。
猜你喜欢
  • 2019-06-25
  • 2021-04-30
  • 2012-01-02
  • 2020-02-13
  • 2017-12-23
  • 2020-10-14
  • 2020-07-11
  • 2021-03-03
  • 1970-01-01
相关资源
最近更新 更多