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?
Mongoose lets you structure queries using chaining or, equivalently, using POJOs in a single function call. Model.
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.
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.
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.
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 });
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With