Search code examples
mongodbexpressmongoosemongoose-middleware

Find a Document where value matched in either field using Mongoose Middleware


I have a list of account connections between source and target accounts so my schema looks like

var ConnectionRequestSchema = new Schema({
  sourceAccountId: {
    type: Schema.ObjectId,
    ref: 'Account'
  },

  targetAccountId: {
    type: Schema.ObjectId,
    ref: 'Account'
  },

  status: {
    type: String,
    enum: ['pending', 'accept', 'decline'],
    trim: true
  }
});

I want to query all documents where the sourceAccountId or the targetAccountId are equal to the queried accountId.

I saw this link how-to-find-a-document-where-either-one-or-another-field-matches-a-value which is relevant for find a docouments using the stand find method in Mongo.

User.findOne({
  $or: [
      {first_name: name},
      {last_name: name},
  ],
}, function(err, user) {
  })

But I would like to do this using Mongoose Middleware and I'm not sure how I would construct this condition.


Solution

  • already you figured out the solution, but you have to make some changes in query

    ConnectionRequest.find({
      $or: [
          {sourceAccountId: "5736eac90a39c2547cb9d911"},
          {targetAccountId: "5736eac90a39c2547cb9d911"},
      ],
    }, function(err, connection) {
    console.log(connection)
      })
    

    then finally you will get the result is array of documents