前端和后端的日志中都可以看到数字数组,但没有保存在数据库中

问题描述 投票:0回答:1

我正在尝试通过生成 4 个随机 8 位数字来复制 google 的备份代码系统。

for(let i = 0; i < 4; i++) {
      let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000);
      backendCodes.push(backendCode);
    }

使用后端服务发布到后端。

constructor(private http: HttpClient) { }

  signUpUser(email: string, password: string, backendCodes: number[]) {
    const url = "http://localhost:3000/signup/api"
    const body = { email, password, backendCodes };
    console.log(body); // Add this line to log the request body
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post(url, body, { headers }).subscribe({
      next: value => console.log(value),
      error: error => console.log(error),
      complete: () => console.log("Complete")
    });
  }

然后将其保存到数据库(MongoDB)中。

app.post("/signup/api", async (req, res) => {
  const { email, password, backupCodes } = req.body;
  console.log(req.body); 
  try {
    const newUser = new User({
      email: email,
      password: password,
      backupCodes: backupCodes,
    });

    await newUser.save();
    console.log("Successful");
    res.status(200).json({ message: "User signed up successfully" });
  } catch (err) {
    console.log("Error: ", err);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

我在期待什么

我本以为一切都会被保存,但发现备份代码是空的。 As shown here

我尝试过的事情

我尝试在发布到后端之前以及将数据保存到数据库之前记录输出

前端

signUpUser(email: string, password: string, backendCodes: number[]) {
    const url = "http://localhost:3000/signup/api"
    const body = { email, password, backendCodes };

    console.log(body); // Test before post

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post(url, body, { headers }).subscribe({
      next: value => console.log(value),
      error: error => console.log(error),
      complete: () => console.log("Complete")
    });
  }

后端

app.post("/signup/api", async (req, res) => {
  const { email, password, backupCodes } = req.body;

  console.log(req.body); // Test before saving to Database

  try {
    const newUser = new User({
      email: email,
      password: password,
      backupCodes: backupCodes,
    });

    await newUser.save();
    console.log("Successful");
    res.status(200).json({ message: "User signed up successfully" });
  } catch (err) {
    console.log("Error: ", err);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

这是结果截图:-

Frontend Console LogBackend Console Log

这是我的架构,如果这是问题:

const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  backupCodes: [Number],
});
javascript angular mongoose mongoose-schema
1个回答
0
投票

客户端和后端日志中显示的数组属性在您的架构中名为 backupCodes,但控制台日志显示属性名称为 backendCodes

© www.soinside.com 2019 - 2024. All rights reserved.