Sunday, 11 June 2017

How can I wait for my async method to finish before saving my Mongoose model to the database? [duplicate]

This question already has an answer here:

It's my first time building an application with Node.js, Express & Mongoose. As stated in the title, I want to wait for my static method (Mongoose) to finish before sending the model to the database. When I add a new record to the database I am missing the order field.

Router:

router.post('/add', FileUpload.setFiles(fields), function (req, res, next) {
    var portfolioItem = new Portfolio({
        title: req.body.title,
        description: req.body.description,
        date: Date.now(),
        thumbnail: FileUpload.getFilePath(req.files.thumbnail[0].filename),
        order: Portfolio.getOrderNumber() // this is null
    });
    portfolioItem.save();
    res.redirect('/');
});

Model:

Portfolio.static('getOrderNumber', function() {
    var query = this.findOne({}, 'order').sort({order:-1}).exec();
    query.then(function(doc) { 
        return doc.order + 10;
    });
});

Result:

{ 
    title: 'Test data',
    description: '',
    date: 2017-06-11T09:35:04.877Z,
    thumbnail: '/uploads/thumbnail-1497173704869.jpeg',
    _id: 593d0ec8c672d9228f647207,
    categories: [],
}

Does anyone know a solution? Much appreciated!



via Jeffrey

No comments:

Post a Comment