如何在钩子中执行多个查询(FeathersJS)

时间:2018-03-01 09:38:53

标签: javascript node.js mongodb mongoose feathersjs

我的mongoDB中有一些用户文档。每个用户都有一个字段职责,这是一个数组。

例如:

用户1:

{ "_id" : ObjectId("5a943dd87d08c3c91b0a36c9"),
  "name" : "Kate Rose",
  "duties": []
}

用户2:

{ "_id" : ObjectId("5a16bfacb7a982bc9b7bd7f9"),
  "name" : "Albert Saxon",
  "duties": []
}

我尝试使用带有mongoose的hook feathersjs中的循环进行一系列查询,如下所示:

patch: [
    function(context){

    var array = [
      { _id: '5a943dd87d08c3c91b0a36c9',    <-- ID of user 1
        data: {                             <-- data to update there duties array
         group: 1,
         comment: 'comment one',
         date: '2018-03-05T00:00:00.000Z'
        }
      },
     { _id: '5a16bfacb7a982bc9b7bd7f9',     <-- ID of user 2
       data: {
         group: 0,
         comment: 'comment two',
         date: '2018-03-05T00:00:00.000Z'
        }
      }
    ]

    var _id = "5a943dd87d08c3c91b0a36c9";

    for(var rowData of array) {

       var userId = rowData._id;
       var data = rowData.data;

       var query = { _id: userId, "duties._id": _id }

       /*
        * I try update selected object in duties array by _id using
        * positional operator and userId
        */

       context.app.service('parents').patch(null, { $set: { "duties.$.comment": data.comment, "duties.$.group": data.group } }, { query }, (error, result) => {

         if(result.length==0){

            /*
             * If result == 0 a new object is added
             */

            context.app.service('parents').update({_id: userId}, { $push: { duties: { _id: _id, date: data.date, comment: data.comment, group: data.group, status: 1 }}}, { query }, (error, result) => {

            });

         }

       });

    }

}]

如上所示,我需要更新职责文件来自数组的每个用户但在我的情况下运行我的函数结果后我收到更新的一个用户并且在那里职责提交的是相同的两个对象(重复),好像两个查询更新了同一个用户。有什么问题?

*我解决了我的问题

我将Promise添加到我的循环中,现在它的效果非常好

for(var rowData of array) {

   new Promise((resolve, reject) => {

   var userId = rowData._id;
   var data = rowData.data;

   var query = { _id: userId, "duties._id": _id }

   context.app.service('parents').patch(null, { $set: { "duties.$.comment": data.comment, "duties.$.group": data.group } }, { query }, (error, result) => {

      if(result.length==0){

         context.app.service('parents').update({_id: userId},
                 { $push: { duties: { _id: _id, date: data.date, comment: data.comment, group: data.group, status: 1 }}},
                 { query });

      }

   });

   });

}

1 个答案:

答案 0 :(得分:0)

尝试删除第一个.patch并自行调用context.app.service('parents').update(...)

它是否会将您想要的内容添加到duties数组中?结果数据结构是什么样的?