public
Last active

Q + Mongoose from StackOverflow

  • Download Gist
q-mongoose-so.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
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();

Original code from http://stackoverflow.com/questions/10545087/how-to-use-module-q-to-refactoring-mongoose-code

var mongoose = require('mongoose');
mongoose.connect('mongo://localhost/test');
var conn = mongoose.connection;

// insert users
conn.collection('users').insert([{/*user1*/},{/*user2*/}], function(err, docs) {
    var user1 = docs[0], user2 = docs[1];

    // insert channels
    conn.collection('channels').insert([{userId:user1._id},{userId:user2._id}], function(err, docs) {
        var channel1 = docs[0], channel2 = docs[1];

        // insert articles
        conn.collection('articles').insert([{userId:user1._id,channelId:channel1._id},{}], function(err, docs) {
            var article1 = docs[0], article2 = docs[1];
        }
    });
};

This should be labeled as an example for the node-mongodb-native driver and not Mongoose as only the native APIs are used here.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.