Home > Enterprise >  How to get referenced obj mongodb
How to get referenced obj mongodb

Time:09-27

So I'm building a web app and using mongodb _ mongoose, I chose this db because I have used it before, and it was a very easy and fast to get rapped up on. I am now running into some use cases where I think a relational database would be a better. But I am here to find out if I can find a fix using mongo db before I rip out all my DB code for mongo.

I have three collections, one of users and one of pending jobs and one of completed jobs. I need to run a pending job, then delete it from the collection and create a completed job entry. Both job collections are connected to a user via an object ID reference list field on my user model. I know how I can get all the pending and completed jobs for a specific user.

const resp = await User.findOne({username:username}).populate(['pendingJobs', 'completedJobs'])

But How do I get the user of a specific job?

  • EDIT

Pending Jobs Model

const pendingJobModel = new mongoose.Schema({
    date:{type:String, required: true, unique:true},
    startTime:{type:String, required: true},
    endTime:{type:String, required: true},
    courseList:{type:[String], required: true},
    member:{type:String},
    clubUsername:{type:String, required: true},
    clubPassword:{type:{token:String, iv:String}, required:true},
    proxy:{type:Boolean, required: true, default:false},
    active:{type:Boolean, required: true, default:false},
},{collection:'pendingjobs'})

module.exports = mongoose.model('PendingJob', pendingJobModel)

Completed Jobs Model

const completedJobModel = new mongoose.Schema({
    date:{type:String, required: true, unique:true},
    successful:{type:String, required: true},
    time:{type:String},
    course:{type:String},
    member:{type:String},
},{collection:'completedjobs'})

module.exports = mongoose.model('CompletedJob', completedJobModel)

User Model

const userModel = new mongoose.Schema({
    username:{type:String, required: true, unique:true},
    password:{type:String, required: true,},
    refreshToken:{type:String, default: ''},
    proxyConfig:{type: mongoose.Types.ObjectId, ref:'Proxy'},
    pendingJobs:{type: [mongoose.Types.ObjectId], ref:'PendingJob'},
    completedJobs:{type: [mongoose.Types.ObjectId], ref:'CompletedJob'}
},{collection:'users'})

module.exports = mongoose.model('User', userModel)

Thanks SO peeps for the help in advanced!!

CodePudding user response:

You can just query user based on the pendingJobs/completedJobs properties:

const user = await User.findOne({ pendingJobs: pending_job_id });

...

const user = await User.findOne({ completedJobs: complited_job_id });
  • Related