我遇到了mongodb的问题
我的数据库中有用户架构,其中有两个引用 为结果而另一个为测试
var userSchema = new mongoose.Schema({
username: String,
email: { type: String , unique: true , required: true} ,
password: String,
gender: { type: String , required: true},
memberShip: {type: String , required: true , default: "pro"},
results: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Result"
}
],
tests: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Test"
}
],
resetPasswordToken: String,
resetPasswordExpiration: Date
});
这是我的结果模式
var resultSchema = new mongoose.Schema({
testName: String,
testId: Number,
totalResult: Number
})
这是测试架构
var testSchema = new mongoose.Schema({
testNumber: Number
})
问题是我想访问html中的这些引用以向用户显示值 我尝试使用填充,但没有用
app.get("/test/:id" , isLoggedIn ,function(req , res){
User.findById(req.params.id).populate("results").populate("tests").exec(
function(error , userResult){
if(error && !userInfo){
console.log(error)
req.flash("error" , "error")
res.redirect("back")
} else {
res.render("testPage" , {userResult: userResult})
}
})
})
答案 0 :(得分:0)
我针对您的问题(根据您的模式)创建了此测试:
//create test object
let test = new TestModel({
testNumber:10,
});
let testSaved = await test.save()
.then((result) => {
console.log(result);
return result;
}).catch((err) => {
console.log(err)
});
//create result object
let result = new ResultModel({
testName: 'test name',
testId: 10,
totalResult: 20
});
let resultSaved = await result.save()
.then((result) => {
console.log(result);
return result;
}).catch((err) => {
console.log(err)
});
//create user object with result and test objects
let user = new UserModel({
username: 'test name',
email: 'test@test.com' ,
password: '123abc',
gender: 'male',
memberShip: "pro",
results: [resultSaved._id],
tests: [testSaved._id],
resetPasswordToken: 'teste',
resetPasswordExpiration: new Date()
});
return await user.save()
.then((result) => {
console.log(result);
return result;
}).catch((err) => {
console.log(err)
});
这是数据库中生成的数据:
此后,我执行了填充命令:
UserModel.findById({_id:"5b4a7169df0fdf56bf3574fb"})
.populate('results')
.populate('tests')
.then((result) => {
console.log('---RESULTS---');
console.log(result._doc.results);
console.log('---TESTS---');
console.log(result._doc.tests);
}).catch((err) => {
console.log(err)
});
效果很好:
尝试执行此代码,我相信这会解决您的问题。
猫鼬有关填充功能的文档:Mongoose Populate