[英]Access data from one collection to another MongoDB
I have this user model made on the nodejs server:我在 nodejs 服务器上创建了这个用户 model:
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:我有这个工作model,它有一个像“外键”这样的用户字段并包含用户_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:您可以填充
Job
model,然后使用以下命令检索user
属性:
const job = await Job.findOne({}).populate('user').exec();
console.log(job.user.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.