node js,mongodb:检查对象是否已存在

时间:2017-08-08 09:32:03

标签: node.js mongodb mongoose

我是nodejs和mongodb的新手,所以如何检查集合中是否已存在对象,请注意,模式中的字段类型是对象还是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');
            }
        }
    });
}

1 个答案:

答案 0 :(得分:7)

一个不错的问题你问,我以前想要完成同样的任务,我使用mongoose-unique-validator第三方npm包,&插件到我们的架构

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

用法:

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

我希望如果这对你有用。