【发布时间】:2019-12-12 23:00:23
【问题描述】:
当使用节点做 mongoose 时,我可以使用 .. 更新 mongo 中的文档。
const account = await userModel
.findOneAndUpdate(
{ 'shared.email': email },
{
$set: {
'shared.username': req.body.username,
...
'shared.country': req.body.country,
'shared.dob': dob,
},
},
{
new: true,
}
)
.exec();
和req.body.username 是null 或'' 和shared.username 已经在mongo 是James
有没有办法保留用户名James 而不是用null 或'' 覆盖它?
userModel 架构是...
const userSchema: Schema = new Schema(
{
email: {
confirmationCode: { type: String, unique: true, index: true },
confirmationSentAt: { type: Date },
confirmed: { type: Boolean, default: false },
},
password: {
hash: { type: String },
resetCode: { type: String, unique: true, index: true },
sentAt: { type: Date },
},
shared: {
avatarId: { type: String },
bio: { type: String },
country: { type: String },
dob: { type: Date },
email: { type: String, required: true, unique: true, index: true },
fullName: { type: String },
gender: { type: String },
language: { type: String, default: 'en' },
location: { type: String },
loggedIn: { type: Boolean, default: true },
username: { type: String, unique: true, index: true },
warningMessage: { type: String, default: 'verify' },
webSite: { type: String },
},
},
{
timestamps: true,
}
);
【问题讨论】:
-
这能回答你的问题吗? stackoverflow.com/a/59094214/11717458
-
不,这不是关于子文档,而是关于当新值为 null 时如何保留原始值,并且它特定于 Mongoose 和 Node.js,例如它与 mongo 和 java 无关
-
你能提供样品请求正文吗?
-
正如我所说的
req.body.username是null或'' -
您可以在问题中添加用户模型代码吗?