首页 > 解决方案 > 猫鼬多对多关系

问题描述

我对 Node.js 和 Mongoose 完全陌生,我遇到了这个问题

Event以及User用户可以参加任何活动的关系,并且活动可以有许多参与用户。

任何时候用户想要参加一个事件,我都可以将事件 id 添加到用户的事件数组中,同时将用户添加到事件的用户数组中,但我认为我想避免这种方法,因为我会存储相同的信息两次.

另一方面,我只能将用户存储到事件的用户数组中,并使用虚拟映射来检索所有用户的事件,但我发现这种方法非常耗时。在我看来,我必须通过每个事件,然后通过所有参与的用户来确定用户是否真的参与。无论如何,如果有办法使用虚函数来做到这一点,我不知道如何localField: userIdforeignField: participants.

解决这个问题的正确方法是什么?

标签: node.jsmongoosenosql

解决方案


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

使用可以在这里阅读更多https://mongoosejs.com/docs/populate.html


推荐阅读