簡體   English   中英

mongoose - 創建新文檔時更新 updatedAt 字段

[英]mongoose - update a updatedAt field while creating a new document

我有以下代碼片段。

const user = await User.findOne({ email: ownerData.email })
            .select('-_id -__v -updatedAt')
            .lean();
        if (!user) {
            throw new HttpException(404, 'User not found');
        }
        await User.deleteOne({ email: ownerData.email });

        console.log(user);

        const newUser = await User.create({
            ...user,
            ...{
                address: ownerData.address,
                city: ownerData.city,
                state: ownerData.state,
            },
            _id: ownerId,
        });
        await newUser.save();

所以基本上我想做的是刪除已經存在的舊用戶創建一個包含舊用戶詳細信息的新用戶。 但不幸的是,即使我沒有使用舊的updatedAt字段,舊的updatedAt字段也被填充到新用戶 object 文檔中。

有可能 ownerId 可以與舊的 _id 相同。 我相信這是因為那個,但我沒有解決這個問題。

謝謝

編輯

我在這個問題上得到了另一個有趣的線索。

因為我正在考慮在代碼的第一行createdAt

const user = await User.findOne({ email: ownerData.email })
            .select('-_id -__v -updatedAt')
            .lean();

新文檔正在從這個createdAt字段中獲取時間。 一旦我刪除並檢查了 newUser 是在新時間創建的。 createdAtupdatedAt之間有什么關系嗎?

我解決了這個問題。 但我沒有一個明確的解釋為什么。 如果有人有完美的解釋,請在下面評論。

我解決了在創建模式后單獨更新updatedAt字段的問題。

const newUser = await User.create({
        ...user,
        ...{
            address: ownerData.address,
            city: ownerData.city,
            state: ownerData.state,
        },
        _id: ownerId,
    });
    newUser.updatedAt = new Date();
    await newUser.save();

我不知道為什么當我喜歡下面的時候這沒有得到更新

const newUser = await User.create({
        ...user,
        ...{
            address: ownerData.address,
            city: ownerData.city,
            state: ownerData.state,
        },
        _id: ownerId,
        updatedAt: new Date()
    });     
    await newUser.save();

在調用save()時將timestamps選項設置為false應該可以解決您的問題。

await newUser.save({timestamps: false});

Here's an issue on the mongoose project 其中解釋了推理。

暫無
暫無

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

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