如何在两个集合之间建立关系

时间:2019-09-17 12:43:54

标签: mongodb express mongoose relationship mongoose-schema

我正在使用nodejs(express)和mongodb(mongoose)创建服务器应用程序。我必须在组织模型和用户模型之间创建关系。创建组织后,我想创建一个将应用于特定组织的用户。一个用户可以申请许多组织。我该怎么办?

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})
      }
    };

1 个答案:

答案 0 :(得分:0)

您可以将组织ID嵌入到用户文档的字符串中

赞这个{ name: "Name", location: "CA", organizations: [123456789, 234567890, ...] }