sql >> Database >  >> NoSQL >> MongoDB

Nodejs Mongoose - hoe vermijd je de callback-hel?

U kunt gebruik maken van chaining van q belofte in nodejs

var Q = require('q');

function findOne(filter) {
    return Q.Promise(function(resolve, reject) {
        Character.findOne(filter, function(err, character) {
            resolve({
                err: err,
                character: character
            });
        });
    });
}

function update(data) {
    return Q.Promise(function(resolve, reject) {
        character.update(data, function(err, characterID) {
            resolve({
                err: err,
                characterID: characterID
            });
        });
    });
}

findOne({ name: 'Sam' }).then(function(data) {
    if (!data.err) {
        // now you can update it.
        return update(data.character);
    } else {
        throw new Error(data.err);
    }
}).then(function(data) {
    if (!data.err) {
        // now you can update it.
        return update(data.characterId);
    } else {
        throw new Error(data.err);
    }
    return findOne({ id: characterId });
}).then(function(data) {
    if (!data.err) {
        // now you can update it.
        return update(data.character);
    } else {
        throw new Error(data.err);
    }
}).catch(function(error) {
    // Handle any error from all above steps
}).done();


  1. Gegevens in Meteor invoegen vanuit Facebook API

  2. $match in $lookup-resultaat

  3. mangoest document.save werkt niet

  4. MongoDB-shell-opdrachten gebruiken op het stuurprogramma van MongoDB 10Gen