如何使用NodeJS获取MongoDB数据以选择选项

时间:2019-06-02 11:53:13

标签: node.js mongodb express mongoose axios

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

这是我到目前为止所做的

  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可视化:

DB

这是我的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);

1 个答案:

答案 0 :(得分:1)

用于mongoose.model()方法

  

第一个参数是模型集合的单数名称   是为了。猫鼬会自动寻找小写的复数形式   型号名称的版本。因此,对于上面的示例,模型   Tank用于数据库中的Tanks收集。

猫鼬试图变得聪明并检测模型名称,但是您可以像这样强制其使用您想要的集合

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

或者在创建模型时,就像这样

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

另外,您尝试访问此参数req.params.authorName时未在路径中对其进行定义,但您在路径中缺少了:

router.route('/authors/authorName')

应该是这样

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

能够获得autherName