如何使用Express从State访问多个MongoDB集合?

rbpvctlc  于 2022-09-18  发布在  Go
关注(0)|答案(0)|浏览(125)

场景介绍

为了使用多对多关系,我尝试从单个MongoDB数据库中的不同集合读取文档。我有一个名为server.js的后端,它从文件university.jsfaculty.js“读取”收集位置。我为它们制作了两个独立的router.get方法。每个方法都可以单独运行,我正在尝试将第二个router.get方法添加到一个称为“Faculties”的不同“状态”中。

示例文件

faculty.js(类似于universities.js)

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

// Create another collection
const FacultyCollection = new Schema(
  {
    name: String,
    amountOfBuildings: Number
  },
  { collection: 'faculties' },
  { timestamps: true ,useUnifiedTopology: true}
);

// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("faculties", FacultyCollection);

router.get.方法(类似于大学)

router.get('/getFaculties', (req, res) => {
  Faculties.find((err, data) => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true, data: data });
  });
});

App.js``stategetFaculties

state = {
        data: [],
        id: 0,
        message: null,
        intervalIsSet: false,
        idToDelete: null,
        idToUpdate: null,
        objectToUpdate: null,
    };

faculties = {
        data: [],
        id: 0,
        message: null,
        intervalIsSet: false,
        idToDelete: null,
        idToUpdate: null,
        objectToUpdate: null,
    };

    componentDidMount() {
        this.getDataFromDb();
        if (!this.state.intervalIsSet) {
            let interval = setInterval(this.getDataFromDb, 5000);
            this.setState({ intervalIsSet: interval });
        }
    }

    componentWillUnmount() {
        if (this.state.intervalIsSet) {
            clearInterval(this.state.intervalIsSet);
            this.setState({ intervalIsSet: null });
        }
    }

    getDataFromDb = () => {
        fetch('http://localhost:3001/api/getFaculties')
                .then((data) => data.json())
                .then((res) => this.setState({ data: res.data }));
    };

示例render显示教师集合中的数据:

render() {
    const { data } = this.state;
    const { faculties } = this.faculties;
    return (
      <div>
        {/*This folds the data of the state into an array with university names*/}
        dat.name={data.map((dat) => dat.name)}

        {/*This is intended to fold the data of the faculties into an array with faculty names*/}
        dat.name={faculties.map((dat) => dat.name)}
     </div>
  );
}

问题

当我还显示该州的大学名称时,如何存储和读取faculty集合的名称(来自/a州)(在同一页上)?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题