1

Here I have two schema:

var personSchema = Schema({
   _id: Schema.Types.ObjectId,
   name: String,
   job: {
       type: Schema.Types.ObjectId,
       ref: 'Job',
   }
});

var jobSchema = Schema({
   _id: Schema.Types.ObjectId,
   title: String,
});

var Job = mongoose.model('Job', jobSchema);
var Person = mongoose.model('Person', personSchema);

Suppose Job has some records:

[{
    "_id" : ObjectId("5b46d41e04cfc922949dcfda"),
    "Title": "Teacher"
}, ...]

When I have some person objects to insert:

[{
     name: 'Peter',
     job: 'Teacher'
}, ...]

Do I need to find the Job's _id and convert the job field to ObjectId type before each save? e.g.

Job.findOne({title: p.job}, (j) => {
    Person.save({name: p.name, job: j._id}).exec(()=>{
         // it's ok!
    )}
})

Or I can use the middleware or populate function to make it easy? Thankyou!

1 Answer 1

2

While saving your person , you are needing a job for it. So this is how you can proceed for the same:

  1. Either create a new job / find an existing job.
  2. Assign the found job's objects _id field to your new Person and save the same.

Eg.code

let person = new Person({
   name : 'TszHin'
});
Job.findOne({ title : 'Abc'})
.then(function(job){
  person.job = job._id;
  person.save();
});
Sign up to request clarification or add additional context in comments.

1 Comment

While this is a good answer for some use cases it does not answer the question. This assumes a lookup record exists. What if the lookup record does not exist, but you still want to insert the record having a specific ObjectId? Surely you must be able to hardcode an ObjectId somehow, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.