【问题标题】:best way of chaining mongoose queries链接猫鼬查询的最佳方式
【发布时间】:2016-11-21 05:45:23
【问题描述】:

我是一名使用 node 和 mongoose 的新手开发人员,想知道用 mongoose 链接查询的最佳方式是什么。我正在像下面那样做,它不起作用。

User.findByIdAndUpdate(req.params._id, user, { upsert: true })
.exec((err, updatedUser) => {
  if (addedCollections) {
    return User.findByIdAndUpdate(req.params._id, { $push: { _collections: { $each: addedCollections } } }, { upsert: true }).exec();
  }
  return new Query;
})
.exec(() => {
  return User.findById(req.params._id).populate('_collections');
})
.exec((err, user) => {
  res.json({ user });
})

如何链接多个查询?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您可以使用 Promise 链,它看起来与您尝试执行的操作非常相似:

    User.findByIdAndUpdate(req.params._id, user, { upsert: true })
        .then(updatedUser => {
          if (addedCollections) {
            return User.findByIdAndUpdate(req.params._id, { $push: { _collections: { $each: addedCollections } } }, { upsert: true });
          }
        })
        .then(() => {
          return User.findById(req.params._id).populate('_collections');
        })
        .then(user => {
          res.json({ user });
        })
        .catch(err => {
          res.status(500).json({ error : err });
        });
    

    【讨论】:

      【解决方案2】:

      您可以使用 Rx 和 mongoose-observables。使用 Rx,.flatMap() 等价于 .then()。

      var Rx = require('rx');
      var observables = require('mongoose-observables');
      
      /* get public header data, list of collections and projects */
      
      router.get("/header", function(req, res) {
        let articleTitle = observables.finder.find(Articles, '{}', ['title'], null);
        let collectionTitle = observables.finder.find(Collections, '{}', ['title'], null);
      
        Rx.Observable.forkJoin([articleTitle, collectionTitle])
          .subscribe(
            (docs) => res.json(docs),
            (err) => console.error(err)
          );
      });
      

      更多示例https://www.npmjs.com/package/mongoose-observables

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-05
        • 2013-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-02
        • 2012-02-03
        相关资源
        最近更新 更多