英文:
How to 'initialize' a TypeScript object?
问题
It appears that when fetching JSON data from a MongoDB database and casting it to a TypeScript class like Team
, the constructor for Team
is not being triggered. This behavior is likely due to how MongoDB's driver for JavaScript/TypeScript works.
MongoDB drivers often create instances of classes based on the data retrieved from the database without calling the class constructor directly. Instead, they typically create objects with the data fields populated but don't invoke the constructor method.
So, in your case, when you fetch a Team
from MongoDB, it's likely being constructed without invoking the constructor you defined. This is a common behavior in many ORMs and database libraries to ensure that objects match the data stored in the database.
If you need to perform initialization logic when a Team
is fetched from the database, you may want to create a separate method within the Team
class to handle that initialization, and then call that method explicitly after fetching the data from MongoDB. This way, you can ensure that your desired setup logic is executed when needed.
英文:
Seems, fetching a json from a mongodb datbase, and cast it will not trigger typescript constructor, why? What is wrong?
I have a Team
class
export class Team {
transformations: { [transformationId: string]: Transformation }
typeTrees: { [ttMakerId: string]: TTMaker }
constructor() {
console.log('NewTree constructor called')
this.transformations = {}
this.typeTrees = {}
}
}
I am downloading a json, which would conform as type to Team:
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<string | null>
) {
const transformationId = req.query.transformationId as string
const text = req.query.text as string
try {
const { mongoClient } = await connectToDatabase()
const db: Db = mongoClient.db('datamapper')
const collection = db.collection<Team>('team')
const team: Team | null = await collection.findOne({
name: 'responsive',
})
But when I add a breakpoint to constructor Team, it will not be hit, why?
答案1
得分: 1
这将使用新关键字创建Team
类的新实例,然后使用Object.assign()
将获取的数据分配给它。这应该会触发构造函数。
英文:
const teamData = await collection.findOne({ name: 'responsive' });
const team = Object.assign(new Team(), teamData);
This will create a new
instance of the Team
class using the new keyword, and then assign the fetched data to it using Object.assign()
. This should trigger the constructor.
答案2
得分: -1
为了初始化一个Team
类的对象,你需要使用new
运算符,如下所示:
const Team: Team = new Team();
通过使用new
运算符,它将触发Team
类的构造函数。
希望能帮助到你!
英文:
To initialize an object of Team
class, you need to use the new
operator like so:
const Team: Team = new Team();
by using the new
operator it will trigger the constructor of the Team class.
Hope it helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论