我正在构建类来查找和快速操作 mongodb 文档上的操作。这是 UserCursor 类。(不是在谈论 MongoDB 的游标)
exports { UserCursor };
class UserCursor {
private __id: object;
constructor(query: { _id?: object, otherId?: number }) {
let { _id, otherId } = query; // Shortens the vars' name
if (!_id && !otherId) return; // Checks if 1 identifier is provided
if (_id) { // If a _id is provided
Users.findOne({ _id }, (err, user) => {
this.__id = user._id;
});
} else if (otherId) { // If a otherId is provided
Users.findOne({ otherId }, (err, user) => {
console.log(1); // Debug, you'll see later
this.__id = user._id;
});
}
}
// Returns this.__id (which should have been initialized in the constructor)
get _id() {
console.log(2)
return this.__id;
}
}
运行时,控制台返回
2
1
我认为您遇到了问题:构造函数中的 mongo 回调在_id
操作后启动。由于每次使用该类时都会激活构造函数,我该如何管理它?