gpt4 book ai didi

node.js - Node js,mongodb : check if an object already exist

转载 作者:可可西里 更新时间:2023-11-01 09:10:31 25 4
gpt4 key购买 nike

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

最佳答案

你问的一个很好的问题,我之前想完成同样的任务,我使用 mongoose-unique-validator 第三方 npm 包,& 插件到我们的模式

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

npm 安装 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);
}

我希望如果这对你也有用。

关于node.js - Node js,mongodb : check if an object already exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com