Home > Blockchain >  How to search in mongoDB if an element is in an array
How to search in mongoDB if an element is in an array

Time:11-30

I'm creating the backend of my project. In this project, there are some groups, and each groups has its partecipant. I would like to make a function in nodejs that retrive all the groups that, in the partecipant field(which is an array), has a given user. Here is the schema of group:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const GroupSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true,
    },founder:{
        type:String,
        required: true, 
    }, partecipants:{
        type: Array,
        required:false,
    }, files: {
        type:Array,
        required: false,
    }
})

const Group = mongoose.model('Group', GroupSchema);

module.exports = Group;

For now, I wrote only this:

const getGroupByUser = (req, res) => {
    const user = req.body.user;

    Group.find()
        .then(files => res.json(files))
        .catch(err => res.status(400).json('ERROR:' err))
}

But it obviusly returns all the groups. I don't know if there is a way to make it in the promise, or if I have to cycle throught the array, like a linear search, but for multiple cases. Any idea? Thank you

CodePudding user response:

const getGroupByUser = (req, res) => {
    const user = req.body.user;
    const id = req.query.id;
    // if id is saved as objectId covert it using Types.ObjectId(id)

    Group.find({partecipants: id})
        .then(files => res.json(files))
        .catch(err => res.status(400).json('ERROR:' err))
}

using {partecipants: id} you tell to mongoDb to find all group that have into the array the userId you pass in query params

  • Related