我有一个mongoose模式如下
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
title:{
type:String,
required: true,
trim: true
},
author:{
type: mongoose.Schema.Types.ObjectId,
ref:'Customer'
},
images: [
{img :{type:String}}
]
},
{ timestamps: true }
);
PostSchema.virtual("images.imgCrop").get(function () {
return `${this.img}/crop/720/720`;
});
module.exports = mongoose.model("Post", PostSchema);
字符串
数据结果为
[
{
"_id": "64cb808d95a1ec6708a8e5e6",
"title": "First Post",
"images": [],
"createdAt": "2023-08-03T10:33:31.253Z",
"updatedAt": "2023-08-03T10:33:31.253Z",
"__v": 0
},
{
"_id": "64cb829a95a1ec6708a8f9ab",
"title": "Next Post",
"images": [
{
"_id": "64cb829a95a1ec6708a8f9ac",
"img": "image001.png"
},
{
"_id": "64cb829a95a1ec6708a8f9ad",
"img": "image002.png"
},
{
"_id": "64cb829a95a1ec6708a8f9ae",
"img": "image003.png"
}
],
"createdAt": "2023-08-03T10:34:02.173Z",
"updatedAt": "2023-08-03T10:34:02.173Z",
"__v": 0
}
]
型
在数据库中我已经有一堆数据,所以我需要在返回查询中修改新的图像路径为imgCrop:“image003.png/crop/720/720”
有没有可能使用mongoose virtual来实现这个功能?
数据提取如下
let posts = await Post.find({}).lean().populate('author ')
所以结果应该如下
[
{
"_id": "64cb808d95a1ec6708a8e5e6",
"title": "First Post",
"images": [],
"createdAt": "2023-08-03T10:33:31.253Z",
"updatedAt": "2023-08-03T10:33:31.253Z",
"__v": 0
},
{
"_id": "64cb829a95a1ec6708a8f9ab",
"title": "Next Post",
"images": [
{
"_id": "64cb829a95a1ec6708a8f9ac",
"img": "image001.png",
"imgCrop": "image001.png/crop/720/720"
},
{
"_id": "64cb829a95a1ec6708a8f9ad",
"img": "image002.png",
"imgCrop": "image002.png/crop/720/720"
},
{
"_id": "64cb829a95a1ec6708a8f9ae",
"img": "image003.png",
"imgCrop": "image001.png/crop/720/720"
}
],
"createdAt": "2023-08-03T10:34:02.173Z",
"updatedAt": "2023-08-03T10:34:02.173Z",
"__v": 0
}
]
型
1条答案
按热度按时间bvhaajcl1#
您需要提取
ImageSchema
并在其上声明一个virtual。字符串
请注意,在使用
lean()
查询时不会调用虚拟对象。因此,您需要删除
lean()
或安装并使用mongoose-lean-virtuals
插件:型