問題:如果用戶輸入的欄位值在更新時實際更改,我試圖找到一種方法來僅更新我的 lastModified 欄位。最初,我在(非聚合)$set 物件中包含了 lastModified 欄位,即使其他更新欄位沒有更改,該物件也總是在 new Date() 更改時更新它。這導致了誤導性的時間戳記錄。
最終,我能夠在更新中使用聚合獲得解決方案,但是,有些事情并不像我預期的那樣有效。我只能假設這是一個錯誤,除非我的理解是錯誤的。請查看代碼片段。
更正:以下都不起作用(但是,如果我用值硬替換欄位路徑,例如將“$firstName”更改為“Steve”,它們確實起作用)
{
$set: {
lastModified: {
$switch: {
branches: [
{
case: {
$ne: ['$firstName', firstName],
},
then: new Date(),
},
{
case: {
$ne: ['$lastName', lastName],
},
then: new Date(),
},
],
default: '$lastModified',
},
},
},
},
{
$set: {
lastModified: {
$switch: {
branches: [
{
case: {
$not: { $eq: ['$firstName', firstName] }
},
then: new Date(),
},
{
case: {
$not: { $eq: ['$lastName', lastName] }
},
then: new Date(),
},
],
default: '$lastModified',
},
},
},
},
如果有人能對此提供一些澄清,我將不勝感激。
編輯:添加了更多詳細資訊
// firstName = 'Steve', lastName = 'Jobs'
// In db, $firstName field = 'John', $lastName field = 'Doe'
// the intention is to compare user input with db fields and
// detect changes using the switch statement
const { firstName, lastName } = req.body
db.collection.updateOne(
{ _id },
[
{
$set: {
firstName,
lastName,
},
},
{
$set: {
lastModified: {
$switch: {
branches: [
{
case: {
$not: {
$eq: ['$firstName', firstName],
},
},
then: new Date(),
},
{
case: {
$not: {
$eq: ['$lastName', lastName],
},
},
then: new Date(),
},
],
default: '$lastModified',
},
},
},
},
],
{ ignoreUndefined: true },
)
我希望資料庫檔案從
{
firstName: 'John',
lastName: 'Doe',
lastModified: ~previous timestamp~
}
到
{
firstName: 'Steve',
lastName: 'Jobs',
lastModified: ~new timestamp~
}
但是我得到
{
firstName: 'Steve',
lastName: 'Jobs',
lastModified: ~previous timestamp~
}
它僅在兩個變數之一被硬編碼時才有效,即
case: {
$not: {
$eq: ['$firstName', firstName],
},
then: 'DOES NOT enter here'
},
case: {
$not: {
$eq: ['John', firstName],
},
then: 'DOES enter here'
},
case: {
$not: {
$eq: ['$firstName', 'Steve'],
},
then: 'DOES enter here'
},
現在,我決定(暫時)使用兩個查詢來更新 lastModified 欄位,但我根本不喜歡這種方法。第二個查詢是:
if (modifiedCount > 0 || upsertedCount > 0) {
dbCollection
.updateOne(filter, update)
.catch((err) => console.error(err))
}
uj5u.com熱心網友回復:
您的更新陳述句不起作用的原因是因為您有兩個$set背靠背的階段。讓我們來看看更新此檔案時會發生什么:
{
firstName: 'John',
lastName: 'Doe',
lastModified: ~previous timestamp~
}
第一$set階段將更新firstName和lastName欄位,產生這樣的檔案:
{
firstName: 'Steve',
lastName: 'Jobs',
lastModified: ~previous timestamp~
}
然后將此生成的檔案傳遞到第二$set階段。在 內部$switch,您正在比較$firstNameandfirstName和$lastNameand的值lastName。但是因為您已經在前一階段更新了這些值,所以它們將始終相同。
您可以將兩個階段合二為一,這樣案例中的$firstName和$lastName變數$switch參考它們的原始值:
db.collection.updateOne(
{ _id },
[
{
$set: {
firstName,
lastName,
lastModified: {
$switch: {
branches: [
{
case: { $ne: [ "$firstName", firstName ] },
then: new Date()
},
{
case: { $ne: [ "$lastName", lastName ] },
then: new Date(),
}
],
default: "$lastModified"
}
}
}
}
],
{ ignoreUndefined: true },
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/389745.html
