收到TypeError:无法读取未定义的属性

时间:2020-02-14 15:58:32

标签: node.js mongodb mongoose

我已经从另一个应用程序复制了代码,并且工作正常。但这给了我TypeError:当我使用api向数据库发出请求时,无法读取未定义的属性查找。 这是我的server.js

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const userRoutes = express.Router();
const PORT = 4000;

let { User } = require("./models/User");

app.use(cors());
app.use(bodyParser.json());

mongoose.connect("mongodb://127.0.0.1:27017/school", { useNewUrlParser: true });
const connection = mongoose.connection;

connection.once("open", function() {
  console.log("MongoDB database connection established successfully");
});

userRoutes.route("/").get(function(req, res) {
  User.find(function(err, users) {
    if (err) {
      console.log(err);
    } else {
      res.json(users);
    }
  });
});
app.use("/users", userRoutes);
app.listen(PORT, function() {
  console.log("Server is running on Port: " + PORT);
});

这是我的用户模型:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let User = new Schema({
  firstName: {
    type: String,
    required: "First name is required"
  },
  lastName: {
    type: String,
    required: "Last name is required"
  },
  emailAddress: {
    type: String,
    required: "Email address is required",
    match: [
      /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      "A valid email address is required"
    ]
  },
  password: {
    type: String,
    required: "Password is required"
  }
});

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

1 个答案:

答案 0 :(得分:0)

您的问题是导入用户架构的错误方法,您可以像这样解决它:

let User = require("./models/User");

现在您的功能可以正常工作了:)