我无法从 Deno 应用程序中的 Mongodb 响应中读取 $iod
I can not read the $iod from Mongodb response in a Deno app
我想写一个简单的注册函数,这是我的代码:
async register(ctx: RouterContext) {
const { email, password } = await ctx.request.body().value;
let user = await User.findOne({ email });
if (user) {
ctx.response.status = 422;
ctx.response.body = { message: "Email is already exist" };
return;
}
const hashedPassword = hashSync(password);
user = new User({ email, password: hashedPassword });
await user.save();
ctx.response.status = 201;
console.log("This is the new useeeeeer", ctx.response.body = {
id: user.id,
name: user.name,
email: user.email
});
}
这是 User.ts
class:
export default class User extends BaseModel {
public id: string = "";
public name: string = "";
public email: string = "";
public password: string = "";
constructor({ id = "", name = "", email = "", password = "" }) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
static async findOne(params: object): Promise<User | null> {
const user = await userCollection.findOne(params);
if (!user) {
return null;
}
return new User(User.prepare(user));
}
async save() {
const { $oid } = await userCollection.insertOne(this);
console.log('this is oid ', $oid);
//delete this.id;
this.id = $oid;
console.log("This is the new UUser", this);
return this;
}
}
问题是它无法正常工作,我在收到的回复中看到 { id: undefined, ...}
。如何获取 MongoDB 为我的用户创建的 id
并将其替换并保存为 User.id
?
新版本的MongoDB好像没有$oid
,必须用_id
代替。虽然我不确定,但可以解决我的问题。
我想写一个简单的注册函数,这是我的代码:
async register(ctx: RouterContext) {
const { email, password } = await ctx.request.body().value;
let user = await User.findOne({ email });
if (user) {
ctx.response.status = 422;
ctx.response.body = { message: "Email is already exist" };
return;
}
const hashedPassword = hashSync(password);
user = new User({ email, password: hashedPassword });
await user.save();
ctx.response.status = 201;
console.log("This is the new useeeeeer", ctx.response.body = {
id: user.id,
name: user.name,
email: user.email
});
}
这是 User.ts
class:
export default class User extends BaseModel {
public id: string = "";
public name: string = "";
public email: string = "";
public password: string = "";
constructor({ id = "", name = "", email = "", password = "" }) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
static async findOne(params: object): Promise<User | null> {
const user = await userCollection.findOne(params);
if (!user) {
return null;
}
return new User(User.prepare(user));
}
async save() {
const { $oid } = await userCollection.insertOne(this);
console.log('this is oid ', $oid);
//delete this.id;
this.id = $oid;
console.log("This is the new UUser", this);
return this;
}
}
问题是它无法正常工作,我在收到的回复中看到 { id: undefined, ...}
。如何获取 MongoDB 为我的用户创建的 id
并将其替换并保存为 User.id
?
新版本的MongoDB好像没有$oid
,必须用_id
代替。虽然我不确定,但可以解决我的问题。