0

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

1
  • if you can give sample data and expected output in JSON Commented Nov 29, 2021 at 15:26

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.