英文:
zod - How to deepPick
问题
I am using zod with fastify. I have a UserModel that consists of the username and device properties. The username field is a string, while the device field is an object (DeviceModel) with "name", "id", and "verified" fields.
During the sign-up process, I want to return the complete user object, but without including certain properties nested inside the DeviceModel. To achieve this, I aim to create a UserSignUpResponse. However, I do not want the entire DeviceModel to be included in the response. I have devised the following solution:
const UserSignUpResponse = UserModel.pick({
username: true,
// unable to perform the following action
device: DeviceModel.pick({
id: true,
name: true,
verified: false,
})
});
My question is whether I should ".pick fields from the UserModel schema and extend it with a device field with the same properties as the DeviceModel?
英文:
I am using zod with fastify. I have a UserModel that consists of the username and device properties. The username field is a string, while the device field is an object (DeviceModel) with "name", "id" and "verified" fields.
During the sign-up process, I want to return the complete user object, but without including certain properties nested inside the DeviceModel. To achieve this, I aim to create a UserSignUpResponse. However, I do not want the entire DeviceModel to be included in the response. I have devised the following solution:
const UserSignUpResponse = UserModel.pick({
username: true,
// unable to perform the following action
device: DeviceModel.pick({
id: true,
name: true,
verified: false,
})
});
My question is whether I should ".pick fields from the UserModel schema and extend it with a device field with the same properties as the DeviceModel ?
答案1
得分: 1
嵌套选择不被允许,但你可以通过使用 `extend` 来绕过:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const UserSignUpResponse = UserModel.pick({
username: true,
}).extend({
device: DeviceModel.pick({
id: true,
name: true,
verified: false,
})
})
<!-- end snippet -->
英文:
Nested pick is not allowed, but you can bypass that with the use of extend
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const UserSignUpResponse = UserModel.pick({
username: true,
}).extend({
device: DeviceModel.pick({
id: true,
name: true,
verified: false,
})
})
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论