猫鼬,快递返回一个空数组

我已经阅读了很多类似的问题,默认情况下在猫鼬上讨论模型名称的复数形式。虽然它似乎不适用于这种情况。问题是它返回一个空数组。我的本地 mongoDB 在“userData”集合中包含 2 个文档,它们如下所示:


{

        "_id" : ObjectId("5dcd0582587ac600ec9323a5"),

        "name" : "John",

        "surname" : "Doe",

        "team" : "CE",

        "project" : "Project1",

        "id" : "2"

}

然后这是我的模型User.js:


const mongoose = require('mongoose');

const { Schema } = mongoose;


const userSchema = new Schema({

    name: 'String',

    surname: 'String',

    team: 'String',

    project: 'String',

    id: 'String'

}, { collection: 'UserData' });


module.exports = mongoose.model('user', userSchema);

这是我的路线userRoutes.js:


const mongoose = require('mongoose');

const User = mongoose.model('user');


module.exports = (app) => {


  app.get(`/`, async (req, res) => {

    let users = await User.find();

    return res.status(200).send(users);

  });


  app.post(`/user`, async (req, res) => {

    let user = await User.create(req.body);

    return res.status(201).send({

      error: false,

      user

    })

  })


  app.put(`/user/:id`, async (req, res) => {

    const { id } = req.params;

    let user = await User.findByIdAndUpdate(id, req.body);

    return res.status(202).send({

      error: false,

      user

    })


  });


  app.delete(`/user/:id`, async (req, res) => {

    const { id } = req.params;

    let user = await User.findByIdAndDelete(id);

    return res.status(202).send({

      error: false,

      user

    })


  })


}


德玛西亚99
浏览 134回答 1
1回答

白衣非少年

在您的架构代码中,您需要定义字段类型,如 name: String 而不是 name: "String"。您的架构必须是这样的:const mongoose = require("mongoose");const { Schema } = mongoose;const userSchema = new Schema(  {    name: String,    surname: String,    team: String,    project: String,    id: String  },  { collection: "UserData" });module.exports = mongoose.model("user", userSchema);此外,您已经创建了用户模型,因此在 userRoute 中无需这样做:const User = mongoose.model('user');您只需要像这样在 userRoute 中正确导入 User 模型。const User = require("../models/User"); // you can change the path if it is not correct最后,要为 post 数据启用 json,您需要将此行添加到您的 index.js:app.use(bodyParser.json()); 通过这些更改,您可以使用这样的 json 主体使用此 URL http://localhost:3000/user创建一个用户:{    "name": "John",    "surname": "Doe",    "team": "CE",    "project": "Project1",    "id": "2"}这将给出如下结果:{    "error": false,    "user": {        "_id": "5dce7f8c07d72d4af89dec57",        "name": "John",        "surname": "Doe",        "team": "CE",        "project": "Project1",        "id": "2",        "__v": 0    }}此时,您将拥有一个 UserData 集合。当您向http://localhost:5000 url发送 get 请求时,您将获得如下用户:[    {        "_id": "5dce75a91cbb4e5f7c5ebfb3",        "name": "John",        "surname": "Doe",        "team": "CE",        "project": "Project1",        "id": "2",        "__v": 0    }]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript