简体   繁体   中英

Mongoose find.where in a schema with an attribute of type ObjectId

I have this schemas:

UserLike

const UserLikeSchema = Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "User",
    required: [true, "User is required"],
  },
  game: {
    type: Schema.Types.ObjectId,
    ref: "Game",
    required: [true, "Game is required"],
  }
});

Game

const GameSchema = Schema({
  title: {
    type: String,
    required: [true, "Title is required"],
  },
  status: {
    type: Boolean,
    default: true,
  },
});

I need to find all UserLikes where populated Game.status are true

I'm trying with a code like this

  const games = await UserLike.find()
  .populate("game")
  .where("game.status")
  .equals(true);

But I can't find a solution:(

You should try using the match option as directed by mongoose docs.

https://mongoosejs.com/docs/populate.html#query-conditions

The query might look something like this:

UserLike.
  find().
  populate({
    path: 'game',
    match: { status: true },
  }).
  exec();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM