I have this user model made on the nodejs server:
const mongoose = require ('mongoose')
const user = new mongoose.Schema({
id:{
type: String,
required: true,
unique: true,
},
name:{
type: String,
required: true,
},
email:{
type: String,
required: true,
unique: true,
},
pass:{
type: String,
required: true
},
company:{
type: String,
},
});
const User = mongoose.model("user", user)
module.exports = User
And I have this jobs model that has a user field like a "Foreign key" and contains the user _id:
const job = new mongoose.Schema({
jobtitle :{
type: String,
required: true,
},
salary:{
type: String,
required: true,
},
jobemail:{
type: String,
required: true,
},
schedule:{
type: String,
required: true
},
user:{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
required: true
},
});
const Job = mongoose.model("job", job)
module.exports = Job
So how can I access the name of the user through the field user in the job's collection?
CodePudding user response:
You can populate the Job
model and then retrieve user
properties with:
const job = await Job.findOne({}).populate('user').exec();
console.log(job.user.name);