程序员。我当前正在尝试从数据中的对象内部删除对象。 我的架构如下:
const Schema = new mongoose.Schema({
userId: { type: String, required: true, unique: true },
currentEmployment: { type: Object },
employmentHistory: [
{
department: { type: String },
lastPosition: { type: String },
joinDate: { type: Number },
leaveDate: { type: Number },
punishmentHistory: [
{
type: { type: String },
reason: { type: String },
date: { type: Number }
}
]
}
],
});
现在,我正在尝试从“currentEmployment”对象中删除“Police”对象。我当前的数据如下:
{
_id: new ObjectId('65e1be295d4d201b8aa902d4'),
userId: '1',
employmentHistory: [],
currentEmployment: {
'Police': {
position: 'Captain',
joinDate: 1709306734,
punishmentHistory: []
}
}
__v: 0
}
我尝试使用以下代码来完成此操作:
data.currentEmployment['Police'] = undefined;
console.log(data);
await data.save();
console.log(data);
声明打印了这样的内容:
{
_id: new ObjectId('65e1f36e4317612bf1266787'),
userId: '1',
employmentHistory: [],
__v: 0
}
为什么整个“currentEmployment”对象从我的数据中删除?
这里有几点需要注意。首先,最好使用
$unset
在一个查询中处理这个问题,如下所示:
const data = await Employee.findOneAndUpdate({
userId: '1',
},{
$unset: {
"currentEmployment.Police": ""
}
},{new: true});
这会将
currentEmployment
设置为空对象。
其次,您会注意到,当您查询该文档时,
currentEmployment
不会显示为空对象。您需要使用 mongosh 或 Compass 并查询集合,然后您就会看到它。
对于 mongoose,由于
minimize: true
默认设置,空对象通常不会保存到文档中,因此当您从查询返回文档时 currentEmployment
不会显示。
要解决这个问题,您需要将
toJSON: { minimize: false }
选项添加到您的架构中,该选项告诉 mongoose 在转换为 JSON 时不要最小化那些空对象。您可以像这样添加此选项:
const Schema = new mongoose.Schema({
userId: { type: String, required: true, unique: true },
//...
//...
}, {
toJSON: { minimize: false }
});