'this' 的外部值被此容器通过 Mongoose Schema Typescript 遮蔽

mongodbtypescript

1个回答

写回答

啦啦啦短短

2025-07-09 17:05

+ 关注

JS
JS

Mongoose是一个流行的Node.JS库,用于在MongoDB数据库中进行对象建模和操作。它提供了一种简洁的方式来定义数据模型和进行数据库查询。在使用Mongoose时,可以使用不同的数据类型来定义模型的属性。其中之一是Schema typescript

Schema typescript是Mongoose的一个扩展,它允许开发人员使用typescript语言来定义模型的结构和验证规则。这使得代码更加类型安全,减少了错误和调试的时间。

在使用Schema typescript时,有一个有趣的特性是外部值被容器通过Mongoose Schema typescript遮蔽。这意味着在模型定义中使用了'this'关键字时,它将引用容器本身,而不是外部值。这种行为可以在某些情况下引起困惑,因此需要注意。

让我们通过一个简单的例子来说明这个问题。假设我们有一个用户模型,其中包含一个名字属性和一个计算属性,用于将名字转换为大写字母。

typescript

import { Schema, model } from 'mongoose';

interface IUser {

name: string;

uppercaseName: string;

}

const userSchema = new Schema<IUser>({

name: String,

uppercaseName: {

type: String,

get() {

return this.name.toUpperCase(); // 'this' is the contAIner, not the external value

},

},

});

const User = model<IUser>('User', userSchema);

在上面的代码中,我们定义了一个用户模型,并在模型的计算属性上使用了'this'关键字。然而,当我们尝试访问计算属性时,我们会发现它返回的是undefined,而不是预期的大写名字。

为了解决这个问题,我们可以改变计算属性的定义,使用一个普通的函数来替代箭头函数,并将外部值作为参数传递进去。

typescript

import { Schema, model } from 'mongoose';

interface IUser {

name: string;

uppercaseName: string;

}

const userSchema = new Schema<IUser>({

name: String,

uppercaseName: {

type: String,

get(this: IUser) {

return this.name.toUpperCase(); // 'this' is the external value

},

},

});

const User = model<IUser>('User', userSchema);

在上面修改后的代码中,我们将'this'的类型限制为IUser,以确保它引用的是外部值。现在,当我们访问计算属性时,它将返回正确的大写名字。

解决方案示例:

typescript

import { Schema, model } from 'mongoose';

interface IUser {

name: string;

uppercaseName: string;

}

const userSchema = new Schema<IUser>({

name: String,

uppercaseName: {

type: String,

get() {

return this.name.toUpperCase(); // 'this' is the contAIner, not the external value

},

},

});

const User = model<IUser>('User', userSchema);

const user = new User({

name: 'John Smith',

});

console.log(user.uppercaseName); // Output: undefined

typescript

import { Schema, model } from 'mongoose';

interface IUser {

name: string;

uppercaseName: string;

}

const userSchema = new Schema<IUser>({

name: String,

uppercaseName: {

type: String,

get(this: IUser) {

return this.name.toUpperCase(); // 'this' is the external value

},

},

});

const User = model<IUser>('User', userSchema);

const user = new User({

name: 'John Smith',

});

console.log(user.uppercaseName); // Output: JOHN SMITH

在使用Mongoose Schema typescript时,需要注意外部值被容器遮蔽的问题。通过明确指定'this'的类型,可以确保引用的是外部值而不是容器本身。这样可以避免潜在的错误并确保代码的正确性。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号