使用Mongoose中间件在任一字段中查找值匹配的文档

Dav*_*wys 2 mongoose mongodb express mongoose-middleware

我有一个源帐户和目标帐户之间的帐户连接列表,因此我的架构看起来像

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
  }
});
Run Code Online (Sandbox Code Playgroud)

我想查询sourceAccountId或targetAccountId等于查询到的accountId的所有文档。

我看到此链接如何找到一个文档,其中一个或另一个字段匹配一个值,该值与在Mongo中使用Stand find方法查找文档有关。

User.findOne({
  $or: [
      {first_name: name},
      {last_name: name},
  ],
}, function(err, user) {
  })
Run Code Online (Sandbox Code Playgroud)

但是我想使用Mongoose Middleware做到这一点,我不确定如何构造这种条件。

kar*_*thi 5

已经找到了解决方案,但是您必须在查询中进行一些更改

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

然后最终您将得到结果是文档数组