我正在使用findOneAndUpdate
与 upsert: true
在选项中。
我想根据文档是否会更新或插入来有条件地设置一个字段。
const find = { email: 'me@me.com' }
const newDoc = { name: 'me', email: 'me@me.com', key: '???' }
const options = { new: true, upsert: true }
Accounts.findOneAndUpdate(find, newDoc, options)
更新时,我需要保留key
单独的字段,但当它是插入时,我需要生成一个新的 key 。
这可能吗..?
最佳答案
您可以在 Mongoose 模型中设置默认值。
例如:
const generateKey = () => {
// ...
return key
}
// in your Mongoose model
key : {
type : String,
default : generateKey
}
然后,不要在发送给 Mongo 的文档中指定 key :
const newDoc = { name: 'me', email: 'me@me.com' } // No key
因此它将在插入时生成一个 key ,否则就保留它。
关于javascript - Mongoose findOneAndUpdate 基于更新或插入的条件字段值..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46070927/