问题描述
我有2个简单的架构,如下所示:
usermodel.js
const mongoose = require('mongoose')
const UserSchema = mongoose.Schema({
firstName: {
type: String,required: true,trim: true
},lastName: {
type: String,phoneNumber: {
type: String,unique: true
},loginInfo: {
type: mongoose.Schema.Types.ObjectId,ref: 'LoginInfo',},{timestamps: true})
UserSchema.index({phoneNumber: 1})
module.exports = mongoose.model('User',UserSchema)
LoginInfoModel.js
const mongoose = require('mongoose')
const LoginInfoSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,ref: 'User',required: true
},password: {
type: String,required: true
}
},{timestamps: true})
module.exports = mongoose.model('LoginInfo',LoginInfoSchema)
从2个模式中可以看出,用户将引用LoginInfo
模式,而LoginInfo
模式将引用User
。两者都是必需的,因为您不能在没有登录信息的情况下创建用户,并且在没有用户的情况下也无法创建登录信息。我对在这里做什么感到困惑?难道我做错了什么?那不是Nosql数据库的行为吗?
我认为问题出在我的设计中。我的解决方案是从user
模式中删除LoginInfo
,但是我不确定是否有更好的方法来实现自己的目标。
我在user
中有LoginInfoModel.js
的原因是这样,我可以通过id轻松查询用户的登录信息,而无需先查询用户。
编辑
我确信问题出在我的设计中,因为这个问题在我的应用程序中都会出现。例如,在usermodel.js
上扩展,如果用户拥有Feed
,那么用户模式自然会看起来像这样
const mongoose = require('mongoose')
const UserSchema = mongoose.Schema({
...,Feed: {
type: mongoose.Schema.Types.ObjectId,ref: 'Feed',UserSchema)
和Feed.js
看起来像这样
const mongoose = require('mongoose')
const FeedSchema = mongoose.Schema({
...,user: {
type: mongoose.Schema.Types.ObjectId,{timestamps: true})
module.exports = mongoose.model('Feed',FeedSchema)
什么是解决此问题的好方法?我似乎无法在网上找到任何东西,也许我的研究是错误的,所以请随时删除链接。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)