Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js , mongodb : check if an object already exist

I'am newbie to nodejs and mongodb, so how can I check if an object already exist in the collections , Note that my field type in the 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');
            }
        }
    });
}
like image 294
nadhem Avatar asked Jan 30 '23 20:01

nadhem


1 Answers

One Of Nice Question You asked, I was suppose to achieve the same task before, I make the use of mongoose-unique-validator third party npm Package, & plugin to 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.'});

Usage:

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

I Hope If this work for you too.

like image 144
Rahil Avatar answered Feb 05 '23 15:02

Rahil