我正在开发一种使用restify和mongoose作为odm的服务。 下面是DB调用后得到的服务响应。
[
{
"_id": "5a548b7c025cfcffdd286e0f",
"createdAt": "2018-01-09T09:29:32.515Z",
"updatedAt": "2018-01-09T10:59:49.159Z",
"subject": "Hello buddy.",
"body": "i am good and fine.",
"category": "email service",
"category_id": "232",
"author": "5a5485834c2274ce5d5e54f8",
"__v": 0,
"images": [
"https://google.com"
],
"email content": [
{
"_id": "5a549dcb80a16b2e822357ae",
"createdAt": "2018-01-09T10:47:39.883Z",
"updatedAt": "2018-01-09T10:47:39.883Z",
"body": "my first comment",
"name": "asdf"
"password":"312312"
"__v": 0,
"photos": []
}
]
}]
Emails.find({_id: emaiId, author_id: author_id}).
populate('emailcontent').exec(function(err, listOfEmails) {
if (err) {
console.error(err);
return next(
new errors.InvalidContentError(err.errors.name.message),
);
}
res.send(listOfEmails);
next();
这只是我回复的一小部分。现在,我不想将所有响应发送回客户端。例如,用户名,密码,电话号码等。所以我有很多我不想发回的数据。我怎么在这里做到这一点?
答案 0 :(得分:0)
在发回数据之前手动删除这些字段:
Proposal
答案 1 :(得分:0)
您可以使用map()
创建一个作为响应发送的新阵列。使用delete
删除字段。
const newListOfEmails = listOfEmails.map((email) => {
delete email._id;
delete email.createdAt;
delete email.updatedAt;
for (let eIdx = 0; eIdx < email["email content"].length; eIdx += 1) {
delete email["email content"][eIdx].password;
}
return email;
});
res.send(newListOfEmails);
答案 2 :(得分:0)
上面的答案是关于黑名单字段,但您也可以尝试列入白名单,例如
const croppedEmails = emails.map( (email) => {
body: email.body,
...(rest of needed fields)
});
使用这种方法,当您添加新的保密字段时,您不必添加新的删除,另一方面,在添加新的公共字段时,您还需要将其添加到上述功能。
答案 3 :(得分:0)
@Mikas我尝试使用map并在res.send()中返回响应。但响应属性不会被删除。
Posts.find({_id: catId}).populate('author')
.exec(function(err, list) {
if(err) {
return next(new errors.InvalidContentError(err.errors.name.message),);};
res.send(200, massageResponse(list, createResponse));
next();
});
});
let createResponse = function (list) {
const trimmedList = list.map((element) => {
delete element.createdAt;
return element;
});
return trimmedList;
}
let massageResponse = function (list, callback) {
return callback(list);
}