简体   繁体   中英

Access data from one collection to another MongoDB

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?

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM