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

41zrol4v  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(92)

我试图复制谷歌的备份代码系统生成4随机8位数。

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

字符串

使用Backend Service发布到后台。

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" });
  }
});

我在期待什么

我希望所有内容都能保存,但看到backupCodes是空的。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],
});

zpf6vheq

zpf6vheq1#

在您的架构中,数组属性名为backupCodes,但控制台日志显示属性名为backendCodes

相关问题