updating a referenced collection in mongo

Viewed 28

I a model schema(created from mongoose)(say collection A) has a reference to another collection(say collection B), then how do you upsert to this referenced collection so that they respect the referenced relationship.

e.g.

A = [...{ 
     name: "a",
     b_id: "EXISTENT_ID"
    }]

B = [..., {
      _id: "EXISTENT_ID",
      "subject": "science",
      "age": 23
    }]

I tried to bulk update like this:

A.bulkWrite([{
     updateOne: {
         filter: {_id: "EXISTENT_ID"},
         update: {$set: {"A.b_id": {subject: "maths", "age": 22}}},
         upsert: true
         }
     }])  

and I get a write error that says: Updating the path 'a.b_id' would create a conflict at 'b_id', I was expecting the associated reference to be updated, since the schema of A is defined as:

Schema({
    name: String,
    b_id: {
      type: mongoose.Types.ObjectId,
      ref: 'B',
      required: true, 
   }
})

The reason why I'd have to bulkWrite A is because the record is to be created if it doesn't exist and the reference linked.

For now I'm using javascript to do things manually making multiple round trips to the database, but, I'd like to use queries if possible. Is something I'm doing currently wrong or is there a mechanism to do this sort of a referenced update? I'd like a header to proceed. Thanks in advance.

0 Answers
Related