如何向架构中的 mongoose 对象数组添加虚拟字段?

问题描述 投票:0回答:1

我有一个猫鼬模式如下

const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
  {
    title:{
        type:String,
        required: true,
        trim: true
    }
    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 来实现这一目标?

这样结果应该变成如下

[
    {
        "_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
    }
]
arrays mongodb object mongoose mongoose-schema
1个回答
0
投票

您需要提取

ImageSchema
并在其上声明一个虚拟。

const ImageSchema = new mongoose.Schema({
  img: { type:String }
});
ImageSchema.virtual('imgCrop').get(function() {
  return `${this.img}/crop/720/720`;
});

const PostSchema = new mongoose.Schema(
  {
    title:{
        type: String,
        required: true,
        trim: true
    }
    images: [ImageSchema]
  },
  { timestamps: true }
);
© www.soinside.com 2019 - 2024. All rights reserved.