所以我目前非常困惑,当涉及到猫鼬填充。猫鼬嵌套填充不工作
我的数据结构如下:用户有一个客户端数组,客户端有一个贷款数组。我正在使用User.find并填充客户端,没有问题。但是,如何填充客户内部的贷款呢?我曾尝试过:
基本上,我们的目标是传递一组客户端,每个客户端都会包含一笔贷款。但现在,我希望这个贷款对象是空的。客户端正在正确填充,但是,贷款引用被传递为未定义。
app.get("/loans", IsLoggedIn, function(req, res) {
User.findById(req.user._id).populate({path: "clients", populate: { path: "loans", model: "loan"}}).exec(function(err, user){
if(err){
console.log(err);
} else{
var amountRepaid = calcRepaid(user.clients.loans);
console.log(user.clients.loans);
res.render("index", {clients: user.clients, amountRepaid: amountRepaid});
}
});
但是,它似乎没有工作,我的模型列在下面,任何帮助表示赞赏!
型号:
客户:
var mongoose = require("mongoose");
var clientSchema = mongoose.Schema({
loans: [{
type: mongoose.Schema.Types.ObjectId,
ref: "loan"
}],
emailAdderess: String,
firstname: String,
lastname: String,
contactNumber: String ,
dateCreated: {type: Date, default: Date.now},
gender: String,
})
module.exports = mongoose.model("Client", clientSchema);
用户:
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = mongoose.Schema({
username: String,
password: String,
firstname: String,
lastname: String,
clients: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Client"
}]
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
贷款:
var mongoose = require("mongoose");
var LoanSchema = mongoose.Schema({
firstName: String,
lastName: String,
email: String,
contactNumber: Number,
amountBorrowed: Number,
length: String,
address: String,
dateDue: Date,
gender: String,
date: { type: Date, default: Date.now },
amountRepaid: { type: Number, default: 0},
loanRepaid: {type: Boolean, default: false}
})
module.exports = mongoose.model("loan", LoanSchema);
在此处提问时,请勿使用外部链接或代码图像,并在问题中包含相关代码。此外,它有助于使该示例具有可再现性,在这种情况下,这意味着包括应产生预期结果的相关数据的“子集”。请参见[如何创建最小,完整和可验证的示例](https://stackoverflow.com/help/mcve)。这里可能的原因是模型之间的引用实际上不匹配。这是你应该看的,如果你不能解决,那么提供足够的数据来返回至少一个结果。 –
你正在使用的猫鼬版本是什么? – ryder
@NeilLunn对不起,在我试图修复它几个小时后,我去睡觉之前,我的坏。我没有包含数据子集的原因是因为我没有使用数据。我想在开头传入一个空数组,然后用户稍后添加它。我会在这个问题上加上这一点。当你说模型之间的引用不匹配时,我不明白你的意思。你可能会扩大一点吗?谢谢。 – Cathal