Mongoose - 如何使用父级的信息自动更新子对象

时间:2015-04-28 16:03:02

标签: node.js mongodb mongoose

有一个特定的理由以下列方式获取信息,因此我无法改变父对象和子对象的关系:

我有一个父对象,其中包含有关多日展会的信息。有一个子对象引用了展会每一天的信息,这些天中的每一天都被称为一个事件。我需要在生成公平对象时自动生成事件子对象。然后我需要从生成的子对象中单独生成一个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
        });
    }
}

};

但是我没有ObjectID,因为没有任何东西进入数据库以生成ID。

我觉得我陷入了困境。任何提示或想法将不胜感激。

1 个答案:

答案 0 :(得分:0)

由于您使用的是Mongoose,您可以从模型构造函数创建一个本地模型实例(假设事件为/library/book/),如下所示:

Event

或者,如果您只有父模型实例(假设为var event = Event(); 为Fair),您可以使用subdoc create方法:

fair

您还可以在构造函数中包含一个对象,前提是它们与预期模型的形式相同。返回的实例将自动包含将由MongoDB使用的对象ID。

也就是说,subdoc数组var event = fair.events.create(); 方法应该自动执行此操作,每个数组项都应该有一个ID。在您保存父文档之前,这些当然都不在远程数据库上。

push