[英]mongoose - update a updatedAt field while creating a new document
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.但不幸的是,即使我没有使用旧的
updatedAt
字段,旧的updatedAt
字段也被填充到新用户 object 文档中。
There is a chance that the ownerId can be the same as the old _id.有可能 ownerId 可以与旧的 _id 相同。 I believe it's because of that, but I don't get around this problem.
我相信这是因为那个,但我没有解决这个问题。
Thanks谢谢
I got another interesting lead on this problem.我在这个问题上得到了另一个有趣的线索。
Since I am considering createdAt
at the very first line of code因为我正在考虑在代码的第一行
createdAt
const user = await User.findOne({ email: ownerData.email })
.select('-_id -__v -updatedAt')
.lean();
The new doc is taking the time from this createdAt
field.新文档正在从这个
createdAt
字段中获取时间。 Once I removed and checked the newUser is being created at a new time.一旦我删除并检查了 newUser 是在新时间创建的。 Is there any relationship between
createdAt
and updatedAt
? createdAt
和updatedAt
之间有什么关系吗?
I solved the issue.我解决了这个问题。 But I don't have a clear explanation to why.
但我没有一个明确的解释为什么。 If anyone have a perfect explanation please comment below.
如果有人有完美的解释,请在下面评论。
I solved the problem with updating the updatedAt
field separately after the schema creation.我解决了在创建模式后单独更新
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();
I don't know why this is not getting updated when I do like below我不知道为什么当我喜欢下面的时候这没有得到更新
const newUser = await User.create({
...user,
...{
address: ownerData.address,
city: ownerData.city,
state: ownerData.state,
},
_id: ownerId,
updatedAt: new Date()
});
await newUser.save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.