2017-08-08 186 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

相關問題