Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose find by reference field

I have a channel schema like this:

const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  }
);

And this is the feedback schema:

const feedbackSchema = new mongoose.Schema({
  channelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "channel",
    require: true
  }
});

How can I find the feedback by channel name?

Feedback.find({channelId.name : 'something'})

Thanks

like image 918
coinhndp Avatar asked Apr 24 '26 08:04

coinhndp


1 Answers

You cant query for a property on an object that doest exists, I would suggest first querying for the channel, grabbing the id and doing the lookup from there.

const channel = await Channel.findOne({ name });
const feedback = await Feedback.find({ channelId: channel._id })
like image 117
Dan Starns Avatar answered Apr 26 '26 00:04

Dan Starns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!