Replies: 1 comment
-
const mongoose = require("mongoose");
const { Schema } = mongoose;
const attachmentSchema = new Schema(
{
filename: { type: String },
filePath: { type: String },
mimeType: { type: String },
size: { type: Number },
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
// Virtual for the URL
attachmentSchema.virtual("url").get(function () {
return `${this.protocol}://${this.host}/media${this.filePath}`;
});
// Middleware to attach the request context
attachmentSchema.pre("find", function () {
const req = this.options?.req;
if (req) {
this.protocol = req.protocol;
this.host = req.get("host");
}
});
const AttachmentModel = mongoose.model("Attachment", attachmentSchema);
// Usage in a controller
const getExample = async (req, res) => {
const example = await ExampleModel.findOne(query)
.populate({
path: "file",
select: "url filePath filename mimeType",
})
.setOptions({ req });
res.json(example);
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello I m struggling to implement a dynamic field to a model and I don t know how to do it. Here I my model:
I need when I get the collection to add a extra field named
url
which should be like thisI don t want to save the url inside database becase maybe I want to change the host in the future and I don t want to store it.
Right know I implemented a solution inside controller but I don t like it too much:
but I m not too happy about this solution. can anybody know a better solution?
Beta Was this translation helpful? Give feedback.
All reactions