2013-01-21 5 views
1

기본적으로 데이터를 삽입하기 전에 특정 데이터가 데이터베이스에 있는지 (mongodb 드라이버를 사용하는지) 확인하고 싶습니다. 따라서 데이터가 존재하는지 확인하기 위해 collection.findOne()을 사용하고 있습니다. collection.insert()이 수행하는 속성의 속성이 null입니다.mongodb에 데이터를 삽입하는 동안 조건을 추가하십시오.

분명히 내 코드가 논리에 따라 작동하지 않습니다. 제발 누군가 나를 밝혀주세요!

내 코드의 일부

:

exports.addUser = function(req, res) { 
    var twitterId = req.body.provider; 
    var userEmail = req.body.email; 

    db.collection('users', function(err, collection) { 
     collection.findOne({'email':userEmail }, function(err, item){ 

      if(item.email === null){ 

       collection.insert({ 
        'email': userEmail, 
        'provider': { 
         'twitter': { 
          'id': twitterId 
         } 
        } 
       }, function(err, result) { 
        if (err) { 
         res.send({'error':'An error has occurred'}); 
        } else { 
         console.log('Success: ' + JSON.stringify(result[0])); 
         res.send(result[0]); 
        } 
       }); 

      }else{ 
       console.log("Email exits "); 
      } 
     }); 


    }); 
} 
+0

내가 단서를 가지고 있다고 생각하면, 그것을 상상할 수있는 방법이있을 수 있습니다 ...? – nihulus

+2

맞아, 당신이하고 싶은 것은'upsert : true '로''collection.update' (http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#update)입니다. 옵션. – JohnnyHK

답변

1

귀하의 ifitem.email을 기대하고 명시 적으로 null로 설정합니다. item.emailitem의 속성이 아니면 해당 if 문은 false으로 평가됩니다. 몇 가지 옵션이 있습니다 그래서

var foo = {bar:'baz'} 
foo.bar // 'baz' 
foo.notSet // undefined 
foo.notSet === undefined // true 
foo.notSet === null // false 

// now if we set foo.notSet to undefined... 
foo.notSet = null // undefined 
foo.notSet === null // true 

, ...

if (item.email) {} else {}; 
if ('email' in item) {} else {}; 
if (item.hasOwnProperty('email')) {} else {}; 

당신이 시도하고 객체 자체에 존재하지 않는 속성을 호출하면 그렇지 않은 경우, JS, 그것은 프로토 타입의 확인합니다 어디서나 프로토 타입에 존재하면 정의되지 않은 값을 반환합니다.

in 연산자는 왼쪽 피연산자가 오른쪽 객체의 속성인지 확인합니다.

마지막으로 Object.hasOwnProperty은 개체의 속성으로 인수를 확인합니다.

모든 말, 즉 {upsert:true}이 최선의 방법 일 것입니다.

+0

예, 어쨌든 지금 upsert를 사용하고 있습니다. – nihulus

관련 문제