简体   繁体   中英

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');
            }
        }
    });
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM