javascriptnode.jsmongojs

MongooseJS find if in array


I have a foreign key field in an array:

const passageSchema = mongoose.Schema({
    input: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Passage'
    }],
});

And I have a passage:

var passage = Passage.findOne({_id: passageID});

And I want to find all passages that have this passage as one of its inputs.

var passages = Passage.find({
        //find if in array
        input: passage //would work if it wasn't an array in schema
 });

Solution

  • if data type == array you could use $in for your query

    here's the example

    var passages = Passage.find({
        input: { $in: [passage] }
    });

    also note, please be careful for using var in javascript