gpt4 book ai didi

node.js - 在客户端和服务器 Mongoose 模型之间共享 typescript 接口(interface)

转载 作者:可可西里 更新时间:2023-11-01 10:17:03 24 4
gpt4 key购买 nike

我试图在客户端代码和服务器代码之间共享一些基本接口(interface)。我在使用接口(interface)在 Mongoose 中创建数据模型时遇到问题。

我遇到的问题是如何访问客户端中的 document._id 属性。我无法在不导致编译错误的情况下将 _id 添加到用户界面,而且我无法在不声明的情况下访问 _id。

我的项目布局:

/src
-/client
--/user.service.ts
-/server
--/models
---/user.model.ts
-/common
--/common.d.ts

用户服务.ts

import { User } from 'common'

deleteUser(user: User): Promise<User> {
return this.http.delete( 'http://someurl/api/users' + user._id )
.toPromise()
.then( resp => resp.json().data as User )
.catch( err => this.errorHandler(err) );
}

用户.模型.ts

import { model, Schema, Document } from 'mongoose';
import { User } from 'common';

let UserSchema = new Schema {
firstName: String,
lastName: String,
email: String
}

export interface UserDocument extends User, Document { }

export var UserModel:Model<UserDocument> = model<UserDocument>('Users', UserSchema);

common.d.ts

declare module 'common' {
export interface User {
firstName: string;
lastName: string;
email: string;
}
}

感谢帮助

最佳答案

您可以将 _id 声明为可选:

export interface User {
_id?: string;
firstName: string;
lastName: string;
email: string;
}

或者您可以为具有 id 的用户设置另一个界面:

export interface PersistedUser extends User {
_id: string;
}

并在需要时转换到它。

关于node.js - 在客户端和服务器 Mongoose 模型之间共享 typescript 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41909207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com