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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With