javascript - 如何从猫鼬用户模型模式中删除条目“对象”
问题描述
我已经弄清楚如何发出 PUT 请求以将 PDF 存储到我的“用户”模式。
我将如何coverLetter
从“req.profile = user”访问该对象以仅在此用户的配置文件中发出删除此条目的请求。
我只设法弄清楚如何从数据库中删除整个用户或文档。
前端:React 后端:Node.js、express、MongoDB、Mongoose
感谢您的任何建议
后端
// Router defintions
router.delete("/user/documents/coverLetter/:userId", deleteData);
router.param("userId", userById);
// Adds user to the Request object
exports.userById = (req, res, next, id) => {
User.findById(id).exec((err, user) => {
if (err || !user) {
return res.status(400).json({
error: "User not found",
});
}
req.profile = user; // adds profile object in req with user info
next();
});
};
/** User Profile Object
{
coverLetter: {
contentType: 'application/pdf',
data: Binary {
_bsontype: 'Binary',
sub_type: 0,
position: 396412,
buffer: <Buffer 25 50 44 46 2d 31 2e 33 0a 25 c4 e5 f2 e5 eb a7 f3 a0 d0 c4 c6 0a 34 20 30 20 6f 62 6a 0a 3c 3c 20 2f 4c 65 6e 67 74 68 20 35 20 30 20 52 20 2f 46 69 ... 396362 more bytes>
}
},
_id: 60c2ef9e13f13d902a07ab0b,
fName: 'gh',
lName: 'h',
email: 'b@gmail.com',
salt: '73bb4607-47bf-407f-9155-0b65d19c21be',
hashed_password: 'a3e08880687ec89344e2a5c6989b1f68bcceee1b',
created: 2021-06-11T05:07:42.472Z,
__v: 0,
updated: 2021-06-11T05:08:01.099Z
}
*/
/**
* Need help with this block
*/
exports.deleteData = (req, res) => {
let user = req.profile
// How do I access the coverLetter to delete it ?
}
/**
* User Schema
*/
const userSchema = new mongoose.Schema({
fName: {
type: String,
trim: true,
required: true
},
lName: {
type: String,
trim: true,
required: true
},
coverLetter: {
data: Buffer,
contentType: String,
},
});
module.exports = mongoose.model("User", userSchema);
前端
export const deleteCover = (userId, token) => {
return fetch(`${process.env.REACT_APP_API_URL}/user/documents/coverLetter/${userId}`, {
method: "DELETE",
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`
}
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
解决方案
您可以使用$unset
运算符对文档进行更新。
/**
* Need help with this block
*/
exports.deleteData = (req, res) => {
let user = req.profile
// To remove the key you can use the '$unset' operator.
user.update({
'$unset': {
'coverLetter': 1
}
})
}
或者,如果要避免使用 MongoDB 运算符,也可以将字段设置为undefined
并调用save
方法。
/**
* Need help with this block
*/
exports.deleteData = (req, res) => {
let user = req.profile
user.coverLetter = undefined;
user.save(callback);
}
推荐阅读
- flutter - 如何在这个 fl-chart 颤动中删除 XY 值
- python - 在 Python 中使用 .csv 列中的列表
- python - 将 pip 升级到 21.1.1 后的软件包安装问题
- git - 您可以将代码从一个分支推送到另一个分支,将不同的下游推送到不同的上游吗
- css - 自定义 CSS Swit React-bootstrap
- google-cloud-platform - 编辑存储桶中对象的权限时收到错误消息
- python - 在 numpy 中对多维数组进行分箱
- django - Django:如何在默认身份验证/登录代码之后添加一个步骤
- google-sheets - Googlesheet:来自初学者的问题,如何使用公式将单列中每 6 个单元格的 [转置] 函数组合起来?
- azure - Spring Boot Cosmos DB 实现中的动态查询