![](/img/trans.png)
[英]How to join/populate 3 tables with one to many relationships in MongoDB/Mongoose?
[英]how to make an inner join with mongodb and mongoose and nestjs?
我有一個帶有 mongodb 的系統,在 nest js 中被 mongoose 泛化了我如何在同一個請求中引入客戶和產品數據
在數據庫中數據是這樣的:
"_id": "621d2137abb45e60cf33a2d4",
"product_id": [
"621cedbf79d68fb4689ef0cb",
"621cedbf79d68fb4689ef0cb",
"621cedbf79d68fb4689ef0cb"
],
"client_id": "621d19f890ec693f1d553eff",
"price": 597,
"__v": 0
我的服務:
findAll() {
return this.sealsModel.find().exec();
}
這種方式不起作用:
findAll() {
var a = this.sealsModel.find().exec()
return this.sealsModel.aggregate([{
$lookup: {
from: 'seals',
localField: 'client_id',
foreignField: '_id',
as: 'client'
}
}])
.exec()
}
但返回這個:
"_id": "621d3e0a1c3bcac85f79f7cc",
"product_id": [
"621cedbf79d68fb4689ef0cb",
"621cedbf79d68fb4689ef0cb",
"621cedbf79d68fb4689ef0cb"
],
"client_id": "621d19f890ec693f1d553eff",
"price": 597,
"__v": 0,
"client": []
Mongo 的$lookup
運算符的替代方法是 Mongoose 的populate
function。為了正確使用它,您首先必須更新您的 model。
您應該有一個如下所示的客戶端 model:
// /models/Client.js
const mongoose = require("mongoose");
const clientSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
... // the rest of your fields
});
module.exports = mongoose.model('Client', clientSchema);
這里要注意的關鍵是最后一行。 model 被稱為“客戶端”。
你要做的改變主要在你的Seal
model:
// /models/Seal.js
const mongoose = require("mongoose");
const sealSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
client_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Client" // We use the same name we gave to our client model in the last file
}
});
module.exports = mongoose.model('Seal', sealSchema);
然后,在您的代碼中,您應該能夠使用:
const Seal = require("YOUR_PATH/models/Seal.js")
Seal.find().populate("client_id")
一個重要的旁注:您的 model 將 mongo ID 顯示為字符串
"_id": "621d3e0a1c3bcac85f79f7cc",
"client_id": "621d19f890ec693f1d553eff", <---
確保字段client_id
是ObjectId
類型,否則它將不起作用:
"client_id": ObjectId("621d19f890ec693f1d553eff")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.