![](/img/trans.png)
[英]Update an embedded array inside an document if it exists otherwise create a new document 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') )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.