2013-08-02 2 views
2

을 존재하지 않을 경우 0으로 설정. 문서에는 고유 한 ID, 마지막 액세스 시간을 저장하는 lastAccess 필드 및 문서 생성시 0으로 설정하고 업데이트하는 경우 1 씩 증가해야하는 timesAccessed 필드가 있습니다., MongoDB를 사용하여 문서를 Upserting 필드를 증가 내가 모음에서 문서를 upsert하는 Node.js를</p> <p>내가하고 싶은 것은에서 MongoDB를 사용하고

// coll is a valid collection 
coll.update(
    {user: accountInfo.uid}, 
    {user: accountInfo.uid, 
    lastAccess: new Date(), 
    $inc: {timesAccessed: 1}, 
    $setOnInsert: {timesAccessed: 0} 
    }, 
    {upsert: true, w: 1}, 
    function(err, result) { 
     if (err) throw err; 
     console.log("Record upserted as " + result); 
    }); 

을하지만, 노드는 말한다 :

나는 시도

MongoError: Modifiers and non-modifiers cannot be mixed 

은 무엇 coincise하고 안전한 방법은이 작업을 수행하는 것입니다?

답변

5

값을 설정하거나 전체 개체를 업데이트/바꾸기해야합니다. 그러니 update(find_query, completely_new_object_without_modifiers, ...) 또는 update(find_query, object_with_modifiers, ...)

플러스, 당신은하지 $를 설정하고 $ setOnInsert 같은 필드 이름과 함께, 당신은 1 : 오부터 카운트가 시작됩니다, 그래서 당신은 update_query에 find_query 항목을 추가 할 필요가 없습니다 수 있습니다 자동으로 추가됩니다.

시도 :

col1.update({ 
    user: accountInfo.uid 
}, { 
    $set: { 
    lastAccess: new Date() 
    } 
    $inc: { 
    timesAccessed: 1 
    } 
}, { 
    upsert: true, 
    w: 1 
}, function(err, result) { 
    if(err) { 
    throw err; 
    } 
    console.log("Record upsert as", result); 
}); 
관련 문제