mongodb没有保存所有数据,它只在文档和节点警告中生成_id & _v

egmofgnx  于 2023-01-16  发布在  Go
关注(0)|答案(1)|浏览(80)

我是新来的,试图创建一个休息API使用NodeJS,express和mongoose。在点击 Postman 后,我只得到了id和版本号,但没有其他信息。
我在postman body〉raw中使用应用程序/json {“名称”:“约翰·西纳”,“用户名”:“新浪”、“密码”:“abc123”}
可能是在安装了bcrypt之后,当我启动我的服务器时,它会发出如下许多警告:
(node:2400) Warning: Accessing non-existent property 'Symbol(Symbol.toStringTag)' of module exports inside circular dependency (Use节点--跟踪警告... to show where the warning was created) s inside (node:2400) Warning: Accessing non-existent property 'instanceOfSchema' of module exports inside circular dependency (node:2400) Warning: Accessing non-existent property '_id' of module exports inside circular depenircular ddency (node:2400) Warning: Accessing non-existent property '_id' of module exports inside circular dependency dency dency app listening at port 3000 connection successfull
我的密码如下:
服务器文件。

const express = require("express");
const mongoose = require("mongoose");
const userHandler = require("./routeHandler/userHandler");

const app = express();
app.use(express.json());

//connection
mongoose.set("strictQuery", true);

mongoose
  .connect("mongodb://0.0.0.0/files", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("connection successfull"))
  .catch((err) => console.log(err));

//application routes
app.use("/user", userHandler);

function errorHandler(err, req, res, next) {
  if (res.headerSent) {
    return next(err);
  }
  res.status(500).json({ error: err });
}

app.listen(3000, () => {
  console.log("app listening at port 3000");
});

架构文件。

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  username: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  status: {
    type: String,
    enum: ["active", "inactive"],
  },
});

module.exports = userSchema;

用户Api文件。

const express = require("express");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../routeHandler/userHandler");
const User = new mongoose.model("User", userSchema);

router.post("/signup", async (req, res) => {
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10);
    const newUser = new User({
      name: req.body.name,
      username: req.body.username,
      password: hashedPassword,
    });
    await newUser.save();
    res.status(200).json({
      message: "SIGN UP DONE",
    });
  } catch {
    res.status(500).json({
      message: "FAILED!",
    });
  }
});

module.exports = router;
dced5bon

dced5bon1#

声明模型并将其导出到架构文件中:

const User = new mongoose.model("User", userSchema);
module.exports = User;

然后,使用以下命令导入:

const User = require('../path/to/user-schema.js);

相关问题