[英]What is the NodeJS mongoDB client equivalent to Mongoose populate?
我正在尝试从使用 Mongoose 切换到使用 JavaScript 的 MongoDB 驱动程序。 在我的一些文件中,我与其他人有关系。 我想知道如何“填充”这些。 使用 Mongoose 我可以执行以下操作:
Collections.find().populate("field")
我想知道如何使用 MongoDB 驱动程序进行等效操作。 是否有一些 function 这样做? 或者,理想情况下,也许可以通过某种方式在聚合管道中做到这一点? 谢谢你的帮助。
是的。 你能行的。
您可以创建一个 function:
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', .....) //function 的 arguments。
将此添加到您的 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);
然后您还添加一个仅用于在同一文件中收集的功能
希望这对你有用。
亲切的问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.