使用mongoose findone时如何删除数组元素
我有以下代码。图像是一个数组,我希望输出除图像中存在的路径以外的所有内容。如何实现这一目标? 图像包含-ID、标题、路径使用mongoose findone时如何删除数组元素,mongoose,Mongoose,我有以下代码。图像是一个数组,我希望输出除图像中存在的路径以外的所有内容。如何实现这一目标? 图像包含-ID、标题、路径 if (dbRes !== null) { res.apiSuccess({ town: dbRes.town, county: dbRes.county, postCode: dbRes.postCode,
if (dbRes !== null) {
res.apiSuccess({
town: dbRes.town,
county: dbRes.county,
postCode: dbRes.postCode,
image: dbRes.image
});
} else {
res.apiError(messages.product.not_found);
}
以下是输出的屏幕截图:
更新:OP共享了对象,该对象显示了更改响应遍历的每个参数的定义 您可以使用mongoose内置函数将dbres转换为对象。然后在响应中传递属性之前,只需使用delete命令从图像中删除属性 根据上面的回答,我们假设dbRes是一个包含属性image、town、country和postCode的对象数组。图像也是一组对象
if (!dbRes) {
// Convert db res to object and destructure attributes
const dataArr = dbRes.toObject(); // Array of objects
const response = dataArr.map((data) => {
const {
town,
county,
postCode,
image = [] // Add default so that we don't have to check for null/undefined
} = data;
const newImageArr = image.map((imageData) => {
// Delete path attribute from image object
delete imageData.path;
return imageData;
});
return {
town,
county,
postCode,
image: newImageArr,
}
});
res.apiSuccess(response);
} else {
res.apiError(messages.product.not_found);
}
资源:
DB级省略
尽管如此,如果在发送响应之前根本不需要使用path变量,那么只需在db级别忽略它即可。这样就不需要遍历对象。在这篇文章中检查mongoose的选择功能
更新:OP共享了对象,该对象显示了更改响应遍历的每个参数的定义 您可以使用mongoose内置函数将dbres转换为对象。然后在响应中传递属性之前,只需使用delete命令从图像中删除属性 根据上面的回答,我们假设dbRes是一个包含属性image、town、country和postCode的对象数组。图像也是一组对象
if (!dbRes) {
// Convert db res to object and destructure attributes
const dataArr = dbRes.toObject(); // Array of objects
const response = dataArr.map((data) => {
const {
town,
county,
postCode,
image = [] // Add default so that we don't have to check for null/undefined
} = data;
const newImageArr = image.map((imageData) => {
// Delete path attribute from image object
delete imageData.path;
return imageData;
});
return {
town,
county,
postCode,
image: newImageArr,
}
});
res.apiSuccess(response);
} else {
res.apiError(messages.product.not_found);
}
资源:
DB级省略
尽管如此,如果在发送响应之前根本不需要使用path变量,那么只需在db级别忽略它即可。这样就不需要遍历对象。在这篇文章中检查mongoose的选择功能
您可以使用
点表示法和mongodb投影
从图像数组中排除路径
字段
db.collection.findOne({
_id: dataId
}, {
"image.path": 0
})
下面的查询假设文档有一个\u id
字段,并且在第一级有一个图像数组。此查询将返回整个文档,仅排除图像
数组中的路径
字段您可以使用点表示法
和mongodb投影
从图像
数组中排除路径
字段
db.collection.findOne({
_id: dataId
}, {
"image.path": 0
})
下面的查询假设文档有一个\u id
字段,并且在第一级有一个图像数组。此查询将返回整个文档,仅排除图像
数组中的路径
字段数据输出,但仍会在输出中获取路径。您能提供您看到的内容吗?您是说您仍然获得路径键,但未定义?或者您仍然可以获得包含数据的路径键吗?我将获得城镇、国家、邮政编码和所有数组图像元素(id、标题、路径)。路径未被删除添加了问题中的图像截图哦,图像是一个数组,这就是它不起作用的原因。将更新数据输出的响应,但仍会获得输出中的路径。您能提供您看到的吗?您是说您仍然获得路径键,但未定义?或者您仍然可以获得包含数据的路径键吗?我将获得城镇、国家、邮政编码和所有数组图像元素(id、标题、路径)。路径未被删除添加了问题中的图像截图哦,图像是一个数组,这就是它不起作用的原因。将更新响应