【问题标题】:How to get MongoDB data to select option using NodeJS如何使用 NodeJS 获取 MongoDB 数据以选择选项
【发布时间】:2020-01-21 18:23:58
【问题描述】:

我正在尝试将 MongoDB 数据填充到 html 选择选项。

这是我到目前为止所做的

  1. 我创建了一个数据库books 并创建了集合AuthorDB

  2. 我手动插入数据(检查它是否真的有效)

  3. 但是当我使用postman 获取数据时,我得到一个空数组 表示没有数据。 (但我已将数据插入AuthorDB 集合)

这是我的server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const BookDB = require('./book-dbmodel');
const AuthorDB = require('./author-dbmodel');

const app = express();
const router = express.Router();

app.use(bodyParser.json());
app.use(cors());
app.use('/books', router);

//connect to books database
mongoose.connect('mongodb://127.0.0.1:27017/books', {useNewUrlParser: true});

const connection = mongoose.connection;
connection.once('open', () => {
    console.log("Connected to MongoDB via port 27017");
});

app.listen(4000, () => {
    console.log('Listening to port 4000');
});

// add book http://localhost:4000/books/add
router.route('/add').post((req, res) => {
    let bookDB = new BookDB(req.body);
    bookDB.save().then((bookDB) => {
        res.status(200).send(`${bookDB} Added!`);
    }).catch((err) => {
        res.status(400).send({message: err});
    });
});


//get all authors http://localhost:4000/books/authors
router.route('/authors').get((req, res) => {
    AuthorDB.find((err, authors) => {
        if(err) throw err;
        res.status(200).send(authors);
    });
});

//get books by author name http://localhost:4000/books/authors/authorName
router.route('/authors/authorName').get((req, res) => {
    let authorName = req.params.authorName;
    BookDB.find({firstName: {$regex: `${authorName}`, $options: "i"}}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});

这是我在前端的App.js

import React, {Component} from 'react';
import axios from 'axios';

const ShowAuthors = (props) => (
    <option value={props.author.firstName}>{props.author.firstName}</option>
);
export default class AddBooks extends Component{

    constructor(props){
        super(props);

        this.state = {
            authorArray: [],
            name: '',
            isbn: 0,
            author: '',
            price: 0,
            yearOfPublication: 0,
            publisher: ''
        }
    }



    //to get author list on dropdown select
    componentDidMount(){
        axios.get('http://localhost:4000/books/authors/')
        .then(authors => {
            console.log(authors.data);
            this.setState({
                authorArray: authors.data
            });
        }).catch(err => {
            console.log(err);
        });
    }

    getAuthors(){   
        return this.state.authorArray.map((currentAuthor, id) => {
            return <ShowAuthors author={currentAuthor} key={id} />
        });
    }

    onSubmit(){

    }
    onChangeName(){

    }
    onChangeISBN(){

    }

    render(){
        return(
            <div className="container">
                <h1>Add Books</h1>

                <form onSubmit={this.onSubmit}>

                <div className="form-group">
                    <label htmlFor="book-name">Book Name</label>
                    <input
                    value={this.state.name} 
                    onChange={this.onChangeName}
                    type="text" className="form-control" id="book-name" aria-describedby="emailHelp" placeholder="Book Name"/>                    
                </div>

                <div className="form-group">
                    <label htmlFor="book-isbn">ISBN</label>
                    <input
                    value={this.state.isbn} 
                    onChange={this.onChangeISBN}
                    type="number" className="form-control" id="book-isbn" aria-describedby="emailHelp" placeholder="ISBN"/>                    
                </div>


                <div className="form-group">
                    <label htmlFor="author-name">Authors</label>
                    <select

                    className="form-control" name="authors" id="authors">
                        {this.getAuthors()} {/* this doesn't return anything but an empty array */}
                    </select>
                </div>

                <div className="form-group">
                    <label htmlFor="book-price">Book Price</label>
                    <input type="number" className="form-control" id="book-price" name="book-price" aria-describedby="emailHelp" placeholder="Book Price"/>                    
                </div>

                <div className="form-group">
                    <label htmlFor="book-year">Published Year</label>
                    <input type="number" className="form-control" id="book-year" name="book-year" aria-describedby="emailHelp" placeholder="Year"/>                    
                </div>                

                <div className="form-group">
                    <label htmlFor="book-publisher">Book Publisher</label>
                    <input type="number" className="form-control" id="book-publisher" name="book-publisher" aria-describedby="emailHelp" placeholder="Publisher"/>                    
                </div>


                </form>
            </div>
        );
    }
}

这是我的 mongodb 可视化:

这是我的AuthorDB 模式模型:

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

let AuthorDB = new Schema({
    firstName: {type: String},
    lastName: {type: String},
    nationality: {type: String}
});

module.exports = mongoose.model('AuthorDB', AuthorDB);

【问题讨论】:

    标签: node.js mongodb express mongoose axios


    【解决方案1】:

    对于mongoose.model() 方法

    第一个参数是模型集合的单数名称 是为了。 Mongoose 自动查找复数,小写 您的型号名称的版本。因此,对于上面的示例,模型 Tank 用于数据库中的坦克集合。

    Mongoose 试图变得聪明并检测模型名称,但您可以强制它使用您想要的集合,如下所示:

    new Schema({..}, { collection: 'AuthorDB' })
    

    或者当你创建模型时,像这样:

    module.exports = mongoose.model('AuthorDB', AuthorDB, 'AuthorDB')
    

    此外,您尝试访问此参数 req.params.authorName,但它未在您的路由中定义,您的路由中缺少 :

    router.route('/authors/authorName')
    

    应该是这样的:

    router.route('/authors/:authorName')
    

    能够获得authorName 值。

    【讨论】:

    • 我没有尝试访问router.route('/authors/:authorName')。我正在尝试访问router.route('/authors')
    • 你能把AuthorDB文件发给你吗,我觉得有问题。
    • 完成 :) 你能看看这个吗?
    • 你刚刚救了我:)
    猜你喜欢
    • 2021-08-14
    • 2019-10-15
    • 2020-03-03
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多