Search code examples
node.jsmongoosepromisees6-promise

Mongoose: write own methods with promise


I want to write some instance / static methods for a model, which uses the mongoose's API and do something before and after using the mongoose's API.

For example, I write my own Article.createArticle method, it checks the data before Article.create, and return article.toObject() after creation.

this is how I want my createArticle works:

Article.createArticle({someKeys: 'SomeData', ...})
    .then(obj => {
         // get plain object here
    });

I tried to write something like this:

Article.Schema.static({
    createArticle: function(data) {
        return new Promise(function(resolve, reject){
            checkDataKeys(data);
            resolve(mongoose.model('Article').create(data)
                .then(article => resolve(article.toObject()));
            );
        });
    },
});

with this createArticle, I only get undefined in then, I must get something wrong.

Also, in addition to make the createArticle work, is there any way to make the code more elegant?

Thanks.


Solution

  • I myself found a methods that works for me. Though I'm not very understand the mechanism, maybe I'll try to work on it later...

    ArticleSchema.static({
        createArticle: function(data) {
            checkDataKeys(data);    // pre works
            return mongoose.model('Article').create(data)
                   .then(obj => {
                       return obj.toObject(); // afterworks
                                              // here, just get the plain obj from doc
                                              // and *return* it
                    });
        },
    });
    

    update: after I searched something about Promise, maybe this could be better.

    ArticleSchema.static({
        createArticle: function(data) {
            checkDataKeys(data);    // pre works
            return mongoose.model('Article').create(data)
                   .then(obj => {
                       return Promise.resolve(obj.toObject());
                       // Some say that this is totally same as directly return
                    })
                    .catch(err => {
                       return Promise.reject(err);
                       // if error, this will ensure the err will be caught
                       // for some async cases
                    });
        },
    });