【问题标题】:Node Express Mongo API return empty result setNode Express Mongo API 返回空结果集
【发布时间】:2021-09-25 16:37:21
【问题描述】:

我将使用 Node Express 和 Mongo 开发 API。我已经手动将数据输入到 mongo db 中,如下所示,当我尝试从 db 中获取数据时,它在 postman 中显示为空。这里我粘贴了我的项目代码以便于弄清楚。

在控制器中返回空结果。


我的项目结构如下所示



db.config.json

module.exports = {
//url: "mongodb://localhost:27017/TestDb"
url: "mongodb://localhost:27017/Users"
 };

server.js

    const express = require("express");
const cors = require("cors");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to Shopping List." });
});

require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

const db = require("./app/models");
db.mongoose
  .connect(db.url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("Connected to the database!");
  })
  .catch(err => {
    console.log("Cannot connect to the database!", err);
    process.exit();
  });

index.js

  const dbConfig = require("../config/db.config.js");

const mongoose = require("mongoose");
mongoose.Promise = global.Promise;

const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.users = require("./user.model.js")(mongoose);
console.log(db.url);
module.exports = db;

user.contoller.js

const db = require("../models");
const User = db.users;

// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {

  User.find({ isAdmin: false })
  .then(data => {
    console.log("datanew"+data); // <-- Empty returns here.. []
    res.send(data);
  })
  .catch(err => {
    res.status(500).send({
      message:
        err.message || "Some error occurred while retrieving user."
    });
  });
};

user.model.js

module.exports = mongoose => {
var schema = mongoose.Schema(
  {
  firstName: String,
  lastName: String,
  password: String,
  email:String,
  isAdmin:Boolean
  },
  { timestamps: true }
);

schema.method("toJSON", function() {
  const { __v, _id, ...object } = this.toObject();
  object.id = _id;
  return object;
});

const User = mongoose.model("user", schema);
return User;
  };

user.route.js

module.exports = app => {
const users = require("../controllers/user.controller.js");

var router = require("express").Router();

// Retrieve all Tutorials
router.get("/", users.findAll);

app.use('/api/users', router);
  };

【问题讨论】:

    标签: node.js mongodb api rest express


    【解决方案1】:

    您似乎手动创建了 MongoDB 集合。用户必须是小写字母,所以从 MongoDB 界面中,更改用户 => 用户,您将被设置。

    您的数据库连接 uri 也应该是:

    module.exports = {
     url: "mongodb://localhost:27017/TestDb"
     };
    

    TestDB 是数据库,而 users 是集合。您的 uri 必须指向您的代码将在其中查询集合的数据库。

    您的用户模型 这只是一个微小的变化,但您希望保持代码一致。用户都应该是大写形式。 MongoDB 可以自动在数据库中使用复数和小型大写字母。

    module.exports = mongoose => {
    var schema = mongoose.Schema(
      {
      firstName: String,
      lastName: String,
      password: String,
      email:String,
      isAdmin:Boolean
      },
      { timestamps: true }
    );
    
    schema.method("toJSON", function() {
      const { __v, _id, ...object } = this.toObject();
      object.id = _id;
      return object;
    });
    
    const User = mongoose.model("User", schema);
    return User;
      };
    
    

    【讨论】:

    • 我有上面所说的变化。服务器正在运行,但我仍然得到空结果。 PS D:\TestProjects\node-express-mongo\user-portal> node server.js mongodb://localhost:27017/TestDb 服务器运行在 8080 端口。连接数据库!数据新
    • 您能否在不设置 isAdmin 的情况下编写您的查询,以便我找出问题所在?例如 User.find({}) .then(data => { console.log("datanew"+data); // { res.status(500).send({ message: err.message || "检索用户时发生错误。" }); });
    【解决方案2】:

    // Actually you can  remove
     index.js     
     db.config.js  files 
    
    // *********
    add in server.js
    const express = require('express')
    const mongoose  = require('monggose') 
    const app = express()
    
    mongoose.connect('mongodb://localhost/TestDb');

    【讨论】:

    • 我已经尝试过了,但仍然出现错误。
    猜你喜欢
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2021-09-04
    • 2021-02-20
    • 2017-12-19
    相关资源
    最近更新 更多