Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way of chaining mongoose queries

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?

like image 445
Benjamin Avatar asked Jul 18 '16 14:07

Benjamin


People also ask

Can Mongoose queries be chained?

Mongoose lets you structure queries using chaining or, equivalently, using POJOs in a single function call. Model.

Can I use $in in Mongoose?

We can specify as many conditions in the query field. But in cases, where we need to filter according to only one field but more than on values. For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator.

What is findOne in Mongoose?

Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.

Is Mongoose front end or backend?

For the Local Library example (and the rest of this topic) we're going to use the Mongoose ODM to access our library data. Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model.


2 Answers

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 });
    });
like image 161
robertklep Avatar answered Oct 18 '22 02:10

robertklep


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

like image 23
Thomas Ducrot Avatar answered Oct 18 '22 02:10

Thomas Ducrot