2014-10-01 59 views
0

在下面的命令,其中foos是一個集合,我「UPSERT」的新項目:如何獲取剛插入到mongodb中的文檔?

foos.update(criteria, 
    { $set: fooUpdate }, 
    { w: 1, upsert: true }, 
    function(err, upsertedFoo) { 
    /* upsertedFoo is actually just count of updated/ inserted rows */ 
} 

我想獲得剛創建新文檔(如果它是一個更新),或已修改的現有文檔(如果已更新)。如果這是不可能的,它的_id也足夠了。

我怎樣才能得到這個?

注意:我使用標準mongodb包。

+0

@wizard findAndModify與upsert一起使用? – bguiz 2014-10-01 14:47:38

回答

0

update函數的回調會給你更新的文檔。例如:

foo.update(conditions, document, options, function(err, result) { 
    if (err) 
    throw new Error(err); 
    console.dir(result); 
} 
+0

問題是,我正在做一個upsert,它與更新不完全相同。 – bguiz 2014-10-01 14:46:47

0

我發現這對docs

// Simple findAndModify command performing an upsert and returning the new document 
// executing the command safely 
collection.findAndModify({d:1}, [['b', 1]], 
    {d:1, f:1}, {new:true, upsert:true, w:1}, function(err, doc) { 
    assert.equal(null, err); 
    assert.equal(1, doc.d); 
    assert.equal(1, doc.f); 
    db.close(); 
}) 

這個 '新' 的選擇似乎是關鍵:

{布爾值,默認值:false}

如果您想要ret設置爲true甕修改對象,而不是原來的。忽略刪除。

希望這會有幫助

相關問題