2017-04-21 38 views
0

我有下面的数据我想要把像下面的数据,但我的架构不允许我做我的,发送像下面的数据请检查。当我把唯一的单{}体其工作正常,但我想不止一个机构如何根据我的需求更改nodejs架构

//Request body 
      { 
      "title" : "test10", 
      "sch_start": "2017-04-3", 
      "sch_end":"2017-04-3" 
     }, 
     { 
     "title" : "test11", 
     "sch_start": "2017-04-4", 
     "sch_end":"2017-04-4" 

     } 

 import mongoose, {Schema} from 'mongoose'; 

    /** 
    * Model to store Calendar entries of Engineer 
    */ 
    var EngineerScheduleSchema = new Schema({ 
     title: { type: String, default: ''},        
     available: { type: Boolean, default: false }, 
     sch_start: { type:Date, default: Date.now }, 
     sch_end: { type:Date, default: Date.now } 
    }); 

    export default mongoose.model('engineer_schedule', EngineerScheduleSchema); 

// Main Model Mongoose Schema 
    schedule: [EngineerSchedule.schema] 

//API Method 
export function updateSchedulecalendar(req, res) { 
    var responseSchedule; 

    //Insert 

    return Engineer.findOneAndUpdate({ _id: req.params.id }, { $addToSet: { schedule: req.body } }, { new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true }).exec() 
     .then((entity) => { 
     if (entity) { 
      responseSchedule = entity.schedule; 
      return EngineerEvents.emit(engineerEvents.updatedSchedule, req.user, entity); 
     } 
     else { 
      return res.status(404).end(); 
     } 
     }) 
     .then(()=> { return res.status(200).json(responseSchedule); }) 
     .catch(handleError(res)); 
    } 

回答

0

首先,既然你想发送很多时间表,您的请求机构应如下所示:

[{ 
      "title" : "test10", 
      "sch_start": "2017-04-3", 
      "sch_end":"2017-04-3" 
     }, 
     { 
     "title" : "test11", 
     "sch_start": "2017-04-4", 
     "sch_end":"2017-04-4" 
    }] 

其次,你应该看看findOneAndUpdate文档,原因在我看来,你是派遣两名调度对象(test10TEST11)将通过REQ指定了一个时间表更新.params.id。这没有多大意义。

如果您希望在单个请求中更新多个计划,那么您可能应该实施批量更新。看看bulk functionality,我会实现这样的事情:

export function updateSchedulecalendar(req, res) { 
    var responseSchedule; 

    var bulk = db.items.initializeUnorderedBulkOp(); 
    // Iterate over every schedule sent by client 
    for(schedule in req.body) { 
    // Generate a new update statement for that specific document 
    bulk.find({ title: schedule.title }).update({ $set: { sch_start: schedule.sch_start, ... } }); 
    } 
    // Execute all updates 
    bulk.execute().then(function() { 
    // Validation 
    }); 
}