【问题标题】:How create relationship between two collections如何创建两个集合之间的关系
【发布时间】:2019-09-18 15:44:37
【问题描述】:

我正在使用 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})
      }
    };

【问题讨论】:

    标签: mongodb express mongoose relationship mongoose-schema


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。我今天找到了这项任务的解决方案。解决方法和你的类似
    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2017-10-18
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多