Node js, mongodb: check if object exists

I am new to nodejs and mongodb, so how can I check if an object exists in collections, Please note that my field type in schema is object or JSON

const BillSchema = mongoose.Schema(
    {

        content: {
            type: Object //or JSON
        },
    }
);

const Bill = module.exports = mongoose.model('Bill', BillSchema);

module.exports.addBill = function (newBill, callback) {
    //Check for all bill titles and content, if newBill doesn't exist then add else do nothing
    Bill.count({ content: newBill.content }, function (err, count) {
        //count == 0 always ???
        if (err) {
            return callback(err, null);

        } else {
            if (count > 0) {
                //The bill already exists in db
                console.log('Bill already added');
                return callback(null, null);
            } else {   //The bill doesnt appear in the db
                newBill.save(callback);
                console.log('Bill added');
            }
        }
    });
}

      

+3


source to share


1 answer


One of the pleasant questions. You asked me, I should have done the same task before, I am using mongoose-unique-validator 3rd party npm package and plugin for our schema

https://www.npmjs.com/package/mongoose-unique-validator

npm install mongoose-unique-validator

var uniqueValidator = require('mongoose-unique-validator');

const BillSchema = mongoose.Schema(

    {
        content: {type:Object , unique:true },
    }
);

BillSchema.plugin(uniqueValidator, {message: 'is already taken.'});

      



Using:

module.exports.addBill = function (newBill, callback) {    
    newBill.save(callback);    
}

      

Hopefully if this works for you too.

+6


source







All Articles