Antoni
Antoni

Reputation: 1433

Mongoose check value from other schema while findAndUpdate

Am I able to check a value from other mongo schema while findAndUpdate?

Example:

Schema 1:

{ _id: 'myId1', name: 'test' }

Schema 2:

{ _id: 'myId2', name: 'test-rest', connectedId: [ 'myId1' ] }

Now I want to check if connectedId has value name while updating

await MongoModel.findOneAndUpdate(
  { 
     _id: "myId",
     connectedId: { connectedValue.name === 'test' } // Now I want check if value from this connectedId has a value equal to my value
  },
  {
    name: "changeName"
  }
)

Upvotes: 0

Views: 39

Answers (1)

Antti_M
Antti_M

Reputation: 968

EDIT: I completely overlooked that you also wanted to update the referenced document. I will howeever leave this answer in case someone else finds it useful.

You should checkout populate from Mongoose documentation. You can add references to other models like this when defining your schema:

connected: [{ type: Schema.Types.ObjectId, ref: 'OtherModelName' }]

OtherModelName should match with however you name your other model when calling mongoose.model('OtherModelName', yourSchema); After that, you can populate the field with some conditions. This example is from the aforementioned documentation:

Story.
  find().
  populate({
    path: 'fans',
    match: { age: { $gte: 21 } },
    // Explicitly exclude `_id`
    select: 'name -_id'
  }).
  exec();

In your case, it would be something like

YourModel
  .find()
  .populate({
    path: 'connected',
    match: {name: 'test'}
  })
  .exec();

Upvotes: 1

Related Questions