数据库:MongoDB
后端:Node.js
数据库中有两个表:User和userDetails。 User表中的ObjectId已在userDetails表中用作userId的引用。现在基于这个userId我想显示userDetails。
我试过制作一个函数并尝试在postman中测试它但我得到了null数据。当我在api测试工具邮递员中测试这个功能时,我没有得到任何用户详细信息。我无法理解为什么我没有得到任何数据。
这是功能:
function getUserDetailByUserId(req, res) {
userDetails.find(req.params.userId, (error, detail) => {
if (error)
res.send(error);
res.json(detail);
}).populate(userId);
}
答案 0 :(得分:0)
使用ObjectId
new mongoose.mongo.ObjectID(req.params.userId)
function getUserDetailByUserId(req, res) {
userDetails.findOne({userId: new mongoose.mongo.ObjectID(req.params.userId)})
.populate(userId)
.exec(function(error, detail){
if (error)res.send(error);
res.json(detail);
});
}
userDetail Schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const userDetailSchema = new Schema({
dateOfBirth: {
type: Date,
required: true
},
gender: {
type: String,
required: true
},
country: {
type: String,
required: true
},
interest: {
type: String,
required: true
},
remarks: {
type: String,
},
userId: {
type: Schema.Types.ObjectId, // Referencing the Registered Users in User Model by their ObjectId reference.
ref: 'User' // Creating a relation between User and UserDetails Model through unique ObjectId.
}
});
module.exports = mongoose.model('UserDetails', userDetailSchema);