我在 mongoose 中有一个字段架构,我正在创建,架构中的属性之一是 _user: {type: Schema.Types.ObjectId, ref: 'User' }
我的问题是 ref: 'User' 如何知道引用用户模型?
下面是我的 googleUserModel.js,当 mongoose.model('users',googleSchema) 时,mongoose 如何知道 ref 是这个 UserModel
ref 是否应该是字段 Schema 的 ref:'users' ,因为那是我在 googleUserModel 中声明 mongoose.model('users',googleSchema) 的方式?也许我的理解完全错误......我是猫鼬的新手,似乎无法理解这一点。
const mongoose = require('mongoose');
const {Schema} = mongoose;
const googleSchema = new Schema({
googleId: String,
credits: {type: Number, default: 15},
displayName: String,
firstName: String,
lastName: String,
image: String,
email: String,
numbers: [{
type: String
}]
})
mongoose.model('users',googleSchema);
例如,我有另一个用于创建联系人的架构,我希望能够将这些联系人添加到另一个名为 Groups 的架构中
这是我的联系方式
const mongoose = require('mongoose');
const { Schema } = mongoose;
const contactSchema = new Schema({
phone_number: {
type: String,
},
country: {
type: String,
},
phone_type:{
type: String
} ,
group: [{
type: Schema.Types.ObjectId, ref: 'Group'
}],
firstName: String,
lastName: String,
company: String,
email: {
type: String,
index: true,
trim: true,
match: [/.+\@.+\..+/, 'Please fill a valid email address'],
sparse: true
},
created: {
type: Date,
default: Date.now
},
error: '',
open: false,
_user: {type: Schema.Types.ObjectId, ref: 'User' },
})
module.exports = mongoose.model('contact', contactSchema)
现在我不会使用像
这样的联系人属性创建我的组架构联系人:[{type: Schema.Types.ObjectId, ref: 'contactSchema' }] ?
像下面这样
const mongoose = require ('mongoose')
const { Schema } = mongoose;
const groupSchema = new Schema ({
title: String,
contacts: [{type: Schema.Types.ObjectId, ref: 'contactSchema' }],
_user: {type: Schema.Types.ObjectId, ref: 'User' },
})
module.exports = mongoose.model('group', groupSchema);