我有一个events
模型,其中guests
可以“注册”并加入活动。每个活动都是一场竞赛,因此每个活动都有最大数量的“客人”,因为某些插槽被标记为“获胜者”。为了确保奖品在访客注册期间不会分配过多,我想在创建活动时预构建嵌入式guests
数组。
然而,当这样做时,我收到了强制转换错误Cast to ObjectId failed for value "{}" (type Object) at path "guests"
,因为我还没有每个客户机的objectIds...
这是通过设计实现的,因为占位符是用“赢家”或“输家”状态构建的,因此客人可以在他们注册并插入阵列时立即得到通知。
有没有一种方法可以让我的events
模型引用guests
并仍然控制:
1.获奖人数
1.在每位客人注册时提供即时反馈(赢家/输家)
Event.js
const eventSchema = new Schema({
qr_name: {
type: String,
required: [true, 'Enter a name for your QR code'],
},
event_name: String,
location_name: String,
description: String,
conversions: [ conversionsSchema ],
image: [ImageSchema],
address: String,
geometry: {
type: {
type: String,
enum: ['Point'],
},
coordinates: {
type: [Number],
}
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
qr: {
type: Schema.Types.ObjectId,
ref: 'Qr'
},
guests: [
{
type: Schema.Types.ObjectId,
ref: 'Guest',
default: null,
},
{
giveaway_interest: {
type: String,
},
redeemed: {
type: String,
default: "No",
date: {
type: Date,
default: Date.now,
},
updatedBy: String,
comments: String,
},
notified: {
type: String,
default: "No",
date: {
type: Date,
default: Date.now,
},
},
winner: {
type: Boolean,
default: 0,
},
},
],
created: {
type: Date, // Captures both date and time
default: Date.now
},
event_start: {
type: Date,
required: [true, 'Date & time of event start required']
},
event_end: {
type: Date,
required: [true, 'Date & time of event end required']
},
}, opts);
Guest.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const guestSchema = new Schema({
email: {
type: String,
default: null
},
firstName: {
type: String,
default: null
},
lastName: {
type: String,
default: null
},
age: {
type: Number,
default: 0
},
gender: {
type: String,
enum: ['m', 'f'],
default: null
},
phone: {
type: Number,
default: 0
},
zip: {
type: Number,
default: 0
},
dateAdded: {
type: Date,
default: Date.now
},
event: {
type: Schema.Types.ObjectId,
ref: 'Event',
attended: String
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
}
});
1条答案
按热度按时间kmbjn2e31#
guests
定义中有2个文档。考虑到你的描述,我相信你的意思是:参见https://mongoosejs.com/docs/schematypes.html#arrays和https://masteringjs.io/tutorials/mongoose/array#document-arrays
我不相信数组的“预构建”是一个理想的解决方案“以确保奖品不会被过度分配”,因为数组项不太方便从一只手操作,并且具有“空”子文档在应用程序端没有广泛的逻辑并不能解决任何问题。除非您有任何其他的理由要保留您的模式,否则我会使用一个单独的查找集合。