2017-09-06 104 views
0

我在選項中使用findOneAndUpdateupsert: trueMongoose findOneAndUpdate基於更新或插入的條件字段值..?

我想根據是否更新或插入文檔來有條件地設置一個字段。

const find = { email: '[email protected]' } 
const newDoc = { name: 'me', email: '[email protected]', key: '???' } 
const options = { new: true, upsert: true } 
Accounts.findOneAndUpdate(find, newDoc, options) 

當它是一個更新,我需要獨自離開key場,但是當它插入我需要生成一個新的密鑰。

這是可能的..?

+1

['$ setOnInsert'](https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/)。它在文檔中。奇怪的是,當你從你的標題中輸入一些相關的詞... –

+0

完美,謝謝! ...是的,這是一個重複,但@JeremyThille這個問題的答案也適用... –

回答

1

您可以在Mongoose模型中設置默認值。

例如:

const generateKey =() => { 
    // ... 
    return key 
} 

// in your Mongoose model 
key : { 
    type : String, 
    default : generateKey 
} 

然後,不指定要發送到蒙戈文檔中的關鍵:

const newDoc = { name: 'me', email: '[email protected]' } // No key 

因此,這將產生上插入一個關鍵,或離開否則。