Last active
August 24, 2017 05:49
-
-
Save domenic/2660323 to your computer and use it in GitHub Desktop.
Q + Mongoose from StackOverflow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
mongoose.connect('mongo://localhost/test'); | |
var conn = mongoose.connection; | |
var users = conn.collection('users'); | |
var channels = conn.collection('channels'); | |
var articles = conn.collection('articles'); | |
var insertUsers = Q.nfbind(users.insert.bind(users)); | |
var insertChannels = Q.nfbind(channels.insert.bind(channels)); | |
var insertArticles = Q.nfbind(articles.insert.bind(articles)); | |
function getInsertedArticles(usersArray) { | |
return insertUsers(usersArray).then(function (insertedUsers) { | |
var channelsArray = insertedUsers.map(function (user) { | |
return { userId: user._id }; | |
}); | |
return insertChannels(channelsArray).then(function (insertedChannels) { | |
var articlesArray = insertedChannels.map(function (channel, i) { | |
return { userId: users[i]._id, channelId: channel.id }; | |
}); | |
return insertArticles(articlesArray); | |
}); | |
}); | |
} | |
getInsertedArticles(someUsers).then( | |
function (insertedArticles) { | |
// you only get here if all three of the above steps succeeded | |
}, | |
function (error) { | |
// you get here if any of the above three steps failed | |
} | |
) | |
.done(); |
This should be labeled as an example for the node-mongodb-native driver and not Mongoose as only the native APIs are used here.
the original code is more readable and natural, and shorter, isn't it?
@newcoder it gets uglier when it you put error handling code.
I was hoping to see something simpler too. The problem here is the Mongoose promise implementation, right? I just want to be clear, so we can address this issue properly.
can you provide full code, i have tried to implement same thing on my server,,but i am getting error.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original code from http://stackoverflow.com/questions/10545087/how-to-use-module-q-to-refactoring-mongoose-code