簡體   English   中英

如何創建新文檔(如果不存在)並使用MongoDB NodeJS本機驅動程序返回新文檔

[英]How to create a new document 'if not exists' and return the new document with MongoDB NodeJS native driver

我要創建一個新文檔(如果不存在),並在創建后返回該新文檔,但是如果該文檔已經存在,我想拋出一個異常。

我認為我這樣做的方式似乎有些拙劣,是否有更好的方法呢?

var query = { name: 'guaranteed to be unique' }
var new_doc = { ... }
var col = // the Mongo collection we're using

col.updateOne(
    query,
    new_doc,
    {upsert: true}
)
.then(update => col.findOne({_id, update.result.upserted.pop()._id}))
.then(doc => console.log(doc))
.catch( exception => console.log('that already exists') )

經過大量搜索 ,我在這篇文章中找到了一些答案 ,但這是一個使用findOneAndUpdatereturnOriginal屬性設置為false的干凈示例

col.findOneAndUpdate(
    query,
    new_doc,
    { upsert: true, returnOriginal:false }
)
.then(update => update.value)
.then(doc => console.log(doc))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM