2017-08-08 184 views
3

我是nodejs和mongodb的新手,所以如何检查一个对象是否已经存在于集合中,请注意我的模式中的字段类型是对象或JSONnode js,mongodb:检查一个对象是否已经存在

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

那么实际上有[[upserts]](https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-option)来做这种事情。当你实际上检查一个现有的字段或几个的组合以查看它们是否存在时,它通常是最有意义的。这里的单个领域没有多大意义。你只是把它放在那里,因为你不知道如何在不定义所有字段的情况下使用猫鼬模式? –

+0

不,我这样做是因为我没有静态字段,每个帖子都有新的json格式@Neil Lunn – nadhem

+0

'新的Schema({},{“strict”:false})''。不需要定义模式,也不需要在一个密钥下进行所有操作。仍然是你的问题是**哪些属性实际上确定它是相同的对象?** –

回答

5

一个有趣的问题你问,我想之前达到同样的任务,我让使用猫鼬器唯一验证第三方NPM包,&插件,我们的模式

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

个NPM安装猫鼬器唯一验证

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

我希望如果这对你的工作了。

+0

感谢您的答复,我会尝试你的解决方案,并告诉你是否(错误) – nadhem

+0

当然@nadhem,也请务必承认在如果它成功地适合你,它也会帮助其他编码者。 :) – Rahil

+0

嗨@nadhem让我们知道这个解决方案是否适合你。 – Rahil

相关问题