![](/img/trans.png)
[英]Issue populating child collections using MongoDB and Mongoose
[英]MongoDB Combining Collections - Not Populating
試圖結合一個客戶和一個帳戶集合。
當我查看使用 res.send(client) 時,我只得到帳戶 ID。 我不確定如何填充字段以將帳戶信息推送到客戶端。 我已經看到了一些一對多的解決方案,但無法弄清楚這兩種方式。
這是我得到的:
{"accounts":["5fba8c2f8e5610374463caab","5fba8d49ae11d93c40ce08d9","5fba8dcfb4192a22d469eeef"],"_id":"5fba8bf1407032134c4c22b4","company":"Testing2","contact":"Testing2","phone":5555,"email":"Testing2","city":"Testing2","state":"Testing2","zip":5555555,"__v":3}
這是我正在使用的路由(基於似乎對他們工作正常的課程(?)):
app.post('/clients/:id/accounts', async (req, res) => {
const { id } = req.params;
const client = await Client.findById(id);
const { name, location, tid } = req.body;
const account = new Account({ name, location, tid })
client.accounts.push(account);
account.client = client;
await account.save();
await client.save();
res.send(client);
// res.redirect(`/clients/${client._id}`)
})
這是我正在使用的兩種模型: 客戶:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const ClientSchema = new Schema({
company: String,
contact: String,
phone: Number,
email: String,
city: String,
state: String,
zip: Number,
accounts: [
{
type: Schema.Types.ObjectId,
ref: 'Account',
},
]
});
module.exports = mongoose.model('Client', ClientSchema);
和帳戶模型:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const AccountSchema = new Schema({
name: String,
location: String,
client: [{
type: Schema.Types.ObjectId,
ref: 'Client'
}],
description: String,
contact: String,
tid: String,
loader: String,
surcharge: Number,
payout: Number,
net: Number,
})
module.exports = mongoose.model('Account', AccountSchema);
任何幫助是極大的贊賞。 提前致謝!!
扎帕之子
如果您使用的是 Moongose,那么populate可能就是您要查找的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.