node.js - 猫鼬多对多关系
问题描述
我对 Node.js 和 Mongoose 完全陌生,我遇到了这个问题
Event
以及User
用户可以参加任何活动的关系,并且活动可以有许多参与用户。
任何时候用户想要参加一个事件,我都可以将事件 id 添加到用户的事件数组中,同时将用户添加到事件的用户数组中,但我认为我想避免这种方法,因为我会存储相同的信息两次.
另一方面,我只能将用户存储到事件的用户数组中,并使用虚拟映射来检索所有用户的事件,但我发现这种方法非常耗时。在我看来,我必须通过每个事件,然后通过所有参与的用户来确定用户是否真的参与。无论如何,如果有办法使用虚函数来做到这一点,我不知道如何localField: userId
将foreignField: participants
.
解决这个问题的正确方法是什么?
解决方案
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
推荐阅读
- azure - 从 Azure 存储帐户下载所有文件
- xcode - Xcode 11 模拟器看起来很奇怪
- ios - 我需要在delegate.m文件中添加代码,我只能在flutter中找到delegate.swift
- java - 我如何在java中使用闭包编译器
- angular - 使用 nginx 作为反向代理在 Azure Service Fabric 中部署 Angular8 应用程序
- python - 告诉脚本等到按钮可点击?
- eclipse - 在 Eclipse 调用时从命令行指定 Eclipse 工作区
- python - 根据先前列中满足的某些条件在数据框中创建新列
- javascript - 无法在阿波罗服务器突变中使用 console.log() 功能
- ruby - 法拉第正在将我的标题从大写更改为大写