[英]mongoose populate not populating the required field
我已經嘗試了幾天嘗試使用生物數據模式值填充用戶文檔。
我一直只獲取用戶數據,而不是兩種模式的組合。
以下是我一直在使用的代碼。
這些是模型:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
這是 mongoose 插件
const passportLocalMongoose = require('passport-local-mongoose')
用戶架構
const UserSchema = new Schema({
email: { type: String, unique: true, required: true},
bios: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Bio'
},
username: String,
level: String,
resetPasswordToken: String,
resetPasswordExpires: Date
});
生物數據架構
const BioSchema = new Schema({
address: String,
age: Number,
gender: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});
使用插件
UserSchema.plugin(passportLocalMongoose, {usernameField: 'email'})
對模式建模
const User = mongoose.model('User', UserSchema, 'user');
const Bio = mongoose.model('Bio', BioSchema, 'bio');
module.exports = {User, Bio}
這些是控制器:
const {User, Bio} = require('../models/users');
module.exports = {
用戶注冊回調 function
signup: async (req, res, next)=>{
await User.register(new User(req.body), req.body.password).then(user=>{
req.login(user, function(err){
if(err) return next(err);
})
生物數據回調 function
postUserDetails: async (req, res, next)=>{
const newBio = new Bio({
address: req.body.address,
age: req.body.age,
gender: req.body.gender,
})
await newBio.save().then(result=>{
console.log(result)
res.redirect('/')
}).catch(err=>{
console.log(err)})
},
獲取請求填充回調 function
getUserDetails: async(req, res, next)=>{
await User.findOne(_req.params._id).populate("bios").then(result=> res.json(result)).catch(err=> console.log(err))
},
}
我沒有得到人口稠密的字段,bios。 我只得到用戶數據作為回報。
有人請幫忙。
只需嘗試findOne({})
和{}
getUserDetails: async(req, res, next)=>{
await User.findOne({_req.params._id}).populate("bios").then(result=> res.json(result)).catch(err=> console.log(err))
},
}
或不帶{}
findById()
getUserDetails: async(req, res, next)=>{
await User.findById(_req.params._id).populate("bios").then(result=> res.json(result)).catch(err=> console.log(err))
您的user
文檔(您在最后一個片段中查詢的那個)是否設置了bios
值,如果有,是否存在具有該確切_id
值的bio
文檔?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.