简体   繁体   中英

Mongoose find() not working on foreign object

Here's my schema.

const Sample = new Schema({
  name: { type: String },
  people: { type: Schema.Types.ObjectId, ref: 'People' }
})

const People = new Schema({
  name: { type: String }
})

Now when I am trying to query the name of People schema using Sample schema.

var queryString = 'name of people'
const results = await Sample.find().populate('people').find({
  'people.name': { $regex: queryString, $options: 'i' },
})

It's working if I am just querying the name of Sample schema but when I'm trying to query the name of People schema on Sample model there are no results.

Mongoose populate supports applying query conditions:

const results = await Sample.find()
    .populate({path: 'people', name: {'APPLY YOUR QUERY CONDITIONS HERE'}});

Check the official documentation:

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

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