简体   繁体   English

猫鼬多对多关系

[英]Mongoose many to many relationship

I am completely new to Node.js and Mongoose and I came up to this problem of having 我对Node.js和Mongoose完全陌生,因此遇到了这个问题

Event and User and a relationship where the User can go to any Event and Event can have many participating users. EventUser以及用户可以进入任何事件和事件的关系可以有许多参与用户。

Any time the user would want to attend an Event I could add the Event id to User's array of events and simultaneously add the User to the Event's array of users but I think that I want to avoid this approach because I would store the same information twice. 每当用户想要参加活动时,我都可以将事件ID添加到用户的事件数组中,同时将用户添加到事件的用户数组中,但是我想避免这种方法,因为我会将相同的信息存储两次。

On the other hand I could only store the User to the Event's array of users and use virtual mapping to retrieve all the User's events but I find this approach quite time consuming. 另一方面,我只能将用户存储到事件的用户数组中,并使用虚拟映射来检索所有用户的事件,但是我发现这种方法非常耗时。 It seems to me that I would have to go through each Event and then through all of its participating users to find out if the user really is participating or not. 在我看来,我将必须遍历每个活动,然后遍历所有参与活动的用户,以查明该用户是否确实在参与。 Anyways if there is a way to do this using the virtual function, i don't know how to map the localField: userId to the array of the Event's foreignField: participants . 无论如何,如果有一种使用虚函数实现此目的的方法,我不知道如何将localField: userId映射到Event的foreignField: participants的数组。

What would be the correct approach to this problem? 解决这个问题的正确方法是什么?

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

const eventSchema = Schema({
  name: String,
  user: [{ type: Schema.Types.ObjectId, ref: 'User' }]
});

const userSchema = Schema({
  name: String,
  event: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});

const Event = mongoose.model('Event', eventSchema);
const User = mongoose.model('User', userSchema);

use can read more here https://mongoosejs.com/docs/populate.html 使用可以在这里阅读更多内容https://mongoosejs.com/docs/populate.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM