Search code examples
node.jselasticsearchmongoosastic

mongoosastic findOneAndUpdate not indexing in elasticsearch


Problem : In my example if i user schema.save then it will indexed in elastic search

but problem starts when i use findOneAndUpdate so it will not index in elastic even if i insert (i.e save)

MovieSchema.findOneAndUpdate(query, reqObject, {
        upsert: true
    }, function(err, results) {
        if (err) {
            if (!update) {
                 var filePath = path.join(__dirname, "../../movie/images/uploads/") + reqObject.imageUrl;
                 fs.unlinkSync(filePath);
             }
            console.log(err)
            callback({
                RESULT_CODE: '-1',
                MESSAGE: 'System error. Please try again'
            });
        } else {

            callback({
                RESULT_CODE: '1',
                MESSAGE: 'Movie inserted'
            });

        }
    });


Solution

  • I fond the answer using findOneAndUpdate

    Example:

    NOTE : pass new : true option upsert: true and it will work

    New option will return updated or created object so internally mongoosastic work like if inserted object or updated object return then onty it will insert in elastic search index

    MovieSchema.findOneAndUpdate(query, reqObject, {
            upsert: true,'new': true
        }, function(err, results) {
            if (err) {
                callback({
                    RESULT_CODE: '-1',
                    MESSAGE: 'System error. Please try again'
                });
            } else {
    
                callback({
                    RESULT_CODE: '1',
                    MESSAGE: 'Movie inserted'
                });
    
            }
        });