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
?
2条答案
按热度按时间bvn4nwqk1#
我解决了这个问题。但是我没有一个明确的解释为什么。如果有人有一个完美的解释,请在下面评论。
我通过在模式创建后单独更新
updatedAt
字段解决了这个问题。我不知道为什么这是没有得到更新时,我喜欢下面
pkln4tw62#
在调用
save()
时将timestamps
选项设置为false
应该可以解决问题。下面是mongoose项目的an issue,其中解释了推理。