有特殊原因,有以下方式的信息,所以我不能改變如何父和子對象涉及:貓鼬 - 如何從父母的信息更新的子對象自動
我有一個包含有關多日展會信息的父對象。有一個子對象引用了展會每一天的信息,這些日子中的每一天都被稱爲事件。我需要在公平對象生成時自動生成事件子對象。然後我需要從生成的子對象中分別生成一個ObjectID的數組。另外,我需要能夠在以後生成不基於公平對象的任意事件對象。這就是爲什麼我有ObjectID的數組,所以我知道自動生成的內容以及用戶生成的內容。
這是我的架構(只是有用的部分):
/**
* This is the main object, the user only supplies information for this object
* name, start and end are all provided by the user, num_days is automatically calculated
*/
var FairSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Fair name',
trim: true
},
start_date: {
type: Date,
required: 'Please provide a start date'
},
end_date: {
type: Date,
required: 'Please provide an end date'
},
num_days: {
type: Number,
required: true,
default: 1
},
events: EventsSchema
});
/**
* This is the child object it should pull all of it's information from the parent at the time the parent is created if
* the parent object has more than one day an event child object is created for each day.
*
* name: The same as the parent object, unless multiday then it's the name plus 'Day #'
* start_date: The same as the parent object unless multiday then it's the parent object time + the child object day
* end_date: the same as the parent object unless multiday then it's the parent object time + the child object day
*
*/
var EventSchema = new Schema({
name: {
type: String,
required: 'Please provide a name for the event',
trim: true
},
start_date: Date,
end_date: Date,
});
我已經試過這樣的事情在我的控制器,然後把它稱爲公平的對象保存之前:
initializeFairEvents = function (fair) {
var fairLengthDays = fair.num_days;
var eventStart = Date.parse(fair.start_date);
var eventEnd = Date.parse(fair.end_date);
var one_day = (24 * 60 * 60 * 1000);
var events = fair.events;
var dailyEventLength = eventEnd - eventStart - one_day*(fairLengthDays-1);
if (events !== null && events.length > 0){}
else {
for (var i = 0; i < fairLengthDays; i++) {
var name, start_date, end_date, preserve;
start_date = (i * one_day) + eventStart;
end_date = (i * one_day) + eventStart + dailyEventLength;
preserve = true;
if (fairLengthDays === 1) {
name = fair.name;
} else {
name = fair.name + ' - day ' + (i + 1).toString();
}
fair.events.push({
name: name,
start_date: start_date,
end_date: end_date,
preserve: preserve
});
}
}
};
但是當時我沒有對象ID的,因爲什麼都沒有去該數據庫有ID的生成。
我覺得我陷入了一個循環。任何提示或想法,將不勝感激。
非常感謝create()方法,我想,正是我在找的。 – MJake