I have tried for several days trying to populate the users document with the bio data schema values.
I keep getting only the user data and not a combination of both schemas.
the following are the codes i have been working with.
These are the models:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
this is the mongoose plugin
const passportLocalMongoose = require('passport-local-mongoose')
the user Schema
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
});
The bio data Schema
const BioSchema = new Schema({
address: String,
age: Number,
gender: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});
using the plugin
UserSchema.plugin(passportLocalMongoose, {usernameField: 'email'})
modelling the Schemas
const User = mongoose.model('User', UserSchema, 'user');
const Bio = mongoose.model('Bio', BioSchema, 'bio');
module.exports = {User, Bio}
These are the controllers:
const {User, Bio} = require('../models/users');
module.exports = {
the user signup callback 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);
})
the bio data callback 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)})
},
get request populate callback function
getUserDetails: async(req, res, next)=>{
await User.findOne(_req.params._id).populate("bios").then(result=> res.json(result)).catch(err=> console.log(err))
},
}
I am not getting the populated field, bios. I'm only getting the user data in return.
Somebody please help.
just try findOne({})
with {}
getUserDetails: async(req, res, next)=>{
await User.findOne({_req.params._id}).populate("bios").then(result=> res.json(result)).catch(err=> console.log(err))
},
}
or findById()
without {}
getUserDetails: async(req, res, next)=>{
await User.findById(_req.params._id).populate("bios").then(result=> res.json(result)).catch(err=> console.log(err))
Does your user
document (one which you are querying in last snippet) has a bios
value set and if it does, is there a bio
document with that exact _id
value?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.