11

I'm a novice developer using node and mongoose, and wondering what the best way of chaining queries with mongoose. I'm doing like below, it's not working.

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 });
})

How can I do chain multiple queries?

2 Answers 2

17

You can use a promise chain, which looks pretty similar to what you're trying to do:

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 });
    });
Sign up to request clarification or add additional context in comments.

Comments

1

You can Use Rx, and mongoose-observables. With Rx, .flatMap() is equivalent to .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)
    );
});

More example at https://www.npmjs.com/package/mongoose-observables

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.