mongoose -在创建新文档时更新updatedAt字段

c9x0cxw0  于 2022-12-13  发布在  Go
关注(0)|答案(2)|浏览(162)

I have the following code snippet.

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();

so basically what I want to do is delete the old user that is already present create a new one with the details of the old one. But unfortunately even though I am not taking the old updatedAt field, the old updatedAt field is getting populated on the new user object doc as well.
There is a chance that the ownerId can be the same as the old _id. I believe it's because of that, but I don't get around this problem.
Thanks

EDIT

I got another interesting lead on this problem.
Since I am considering createdAt at the very first line of code

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

The new doc is taking the time from this createdAt field. Once I removed and checked the newUser is being created at a new time. Is there any relationship between createdAt and updatedAt ?

bvn4nwqk

bvn4nwqk1#

我解决了这个问题。但是我没有一个明确的解释为什么。如果有人有一个完美的解释,请在下面评论。
我通过在模式创建后单独更新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();
pkln4tw6

pkln4tw62#

在调用save()时将timestamps选项设置为false应该可以解决问题。

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

下面是mongoose项目的an issue,其中解释了推理。

相关问题