Search code examples
mongodbexpressmongooserelationshipmongoose-schema

How create relationship between two collections


I'm creating server app using nodejs(express) and mongodb(mongoose). I must create relationships between Organization model and Users model. After creating an organization, I want to create a user that will apply to a specific organization. One user can apply to many organizations. How can I do this?

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// UserShema
    const UserSchema = Schema({
      login: {
        type: String,
        require: true,
        unique: true
      },
      password: {
        type: String,
        require: true
      },
      organization: {
        ref: "Organization",
        type: Schema.Types.ObjectId
      }
    });

    // Organization Schema
    const OrganizationSchema = Schema({
      label: {
        type: String
      },
      users: [{
        type: Schema.Types.ObjectId,
        ref: "Users"
      }]
    });

    //For now I have simple route for creating an Organization.
    // request: 
    //  {
    //    "label": "testOrg"
    //  }

    exports.createOrganization = async (req, res) => {
      try {
        const org = await new Organization(req.body);
        await org.save();
      } catch (error) {
        return res.status(500).json({error})
      }
    }

    //And I have this route for user registration

    exports.signup = async (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      };
      const {login} = req.body;
      try {
        const checkUser = await Users.findOne({login});
        if (!checkUser) {
          const user = await new Users(req.body);
          await user.save();
          return res.status(200).json({ user });
        } else {
          return res.status(400).json({error: "User already exist"})
        }
      } catch (error) {
        return res.status(500).json({error})
      }
    };

Solution

  • You could embed the organization id into a string into the user document

    Like this { name: "Name", location: "CA", organizations: [123456789, 234567890, ...] }