猫鼬查找查询以错误的顺序给出结果

时间:2019-12-01 05:08:15

标签: node.js mongodb mongoose mongodb-query

我正在将更新的 _id 数组保存到文档中的数组。如果我检查文档,一切都会很好地更新,但是当我随后使用新的find查询填充时,它就无法正常工作。 填充对我不起作用,所以我决定手动进行处理,虽然可以成功填写,但是顺序错误。


export function sort_update(req, res) {

  Action.findOneAndUpdate({
    _id: req.query.action
  }, {
    child_actions: req.body.newArray
  }, {
    useFindAndModify: false, new: true
  }, function(err, doc) {
    if (err) return res.send(500, {
      error: err
    });

    console.log("child action id strings after update", doc.child_actions); // ["1", "2"] correct!

    Action.find({'_id': {$in: doc.child_actions }}, function(err, child_action_docs) {
      if (err) return res.send(500, {
        error: err
      });

      console.log("child action objects after fill", child_action_docs); // [{ _id: "2" }, { _id: "1" }] wrong!

      doc.child_actions = child_action_docs;
      res.send(doc);
    });

  });
}

为什么它们的顺序错误? {'_id': {$in: doc.child_actions }}根本不保证任何订单吗?我是否必须故意将对象重新排序为doc.child_actions顺序,还是有一种更简单的方法告诉mongodb将顺序保留在原始数组中?

0 个答案:

没有答案