【问题标题】:How to query a single document from a Mongodb collection with react如何使用 React 从 Mongodb 集合中查询单个文档
【发布时间】:2019-02-22 10:15:55
【问题描述】:

我正在尝试使用 react 前端和节点后端构建一个搜索栏,这将让我从 mongoDB 集合中搜索客户 ID,然后从集合中拉出单个文档中的所有数据并显示它在我的反应应用程序上。

目前,如果可能的话,我只是想让单个文档位工作。目前,它拉下整个集合。

我当前的节点代码:

搜索路由器

const express = require('express');
const app = express();
const tfiPaintCodesRouter = express.Router();

const PaintInfoSchema = require('../models/PaintInfoSchema.js');

tfiPaintCodesRouter.route('/get').get(function (req, res) {
  const tfipaintcode = new PaintInfoSchema(req.body);
  console.log(req.body)
  tfipaintcode.save()
    .then(tfipaintcode => {
        res.json('Got data!!');
    })
    .catch(err => {
    res.status(400).send("unable to get data");
    console.log('CustomerID is required', err.res);
    });
});

tfiPaintCodesRouter.route('/').get(function (req, res) {
    PaintInfoSchema.find(function (err, tfipaintcodes){
    if(err){
      console.log('this is an error!', err.res);
    }
    else {
      res.json(tfipaintcodes);
    }
  });
});

module.exports = tfiPaintCodesRouter;

使用 mongoose 的 Mongo 架构。

const mongoose = require('mongoose')
var uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;

  // Create schema
 const PaintInfoSchema =  new Schema({
        customerID: {
            required: true,
            index: true,
            unique: true,
            type: String
        },
        companyName: {
            index: true,
            type: String
        },
        curtainCodes: {
            index: true,
            type: String
        },
        sinageCodes: {
            index: true,
            type: String
        },
        Notes: {
            index: true,
            type: String
        },
        Method: {
            index: true,
            type: String
        },
    },{
      collection: 'tfiPaintCodes'
    });
PaintInfoSchema.plugin(uniqueValidator);
module.exports = mongoose.model('PaintInfoSchema', PaintInfoSchema)

我目前的反应代码是:

import React from 'react';
import {  Form, FormGroup, Input, Container, Row, Col } from 'reactstrap';
import './Search.css'
import axios from 'axios'

class Search extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
          searchInfo: []
    };  
  }

  handleInputChange = (event) => {
    event.preventDefault();
    const { value } = event.target;
    console.log('Value', value)
    this.setState({
      query: value
    });

    this.search(value);

  };

  search = query => {
      axios.get('http://localhost:3001/getData')
       .then(res =>{
        const searchInfo = (res.data || []).map(obj => ({ 
          company: obj.companyName,
          sinage: obj.sinageCodes,
          method: obj.Method,
          notes: obj.Notes}));


          this.setState({ searchInfo });
       })
    };

  componentDidMount() {
    this.search("");
  }

    render() {
        return(
            <Container>
                 <Form>
                    <Row>
                        <Col md={{ size: 6 ,offset: 3}}>
                            <FormGroup className="SearchBar">
                              <Input onChange={this.handleInputChange} type="search" name="search" id="exampleSearch" placeholder="search" />
                            </FormGroup>
                        </Col>
                    </Row>

                </Form>
       <ul>
        {this.state.searchInfo.map(function(searchInfo, index){
          return (
              <div key={index}>
                <h1>NAME: {searchInfo.company}</h1>
                <p>{searchInfo.sinage}</p>
                <p>{searchInfo.method}</p>
                <p>{searchInfo.notes}</p>
              </div>
            )
          }
        )}
      </ul>
            </Container>
        );
      }
    }
export default Search

上面的代码查询了mongodb,然后把我的集合中存储的所有数据都拉下来了,这里是返回数据的图片。

前端显示的数据

但我想知道是否可以只拉下该集合中的一个文档,所以它只会显示一个名称:然后是其他 4 位数据。

我将数据存储在 Mlab 中,这是存储在我的集合中的文档的屏幕截图。

MongoDB 中的数据

这可能吗?谢谢!

【问题讨论】:

  • 使用 res.data[0] 只能从响应中获取一个对象

标签: node.js mongodb reactjs


【解决方案1】:

最好的方法是从数据库中只提取一个文档(如果您不需要更多文档)。

Mongoose 与任何其他 ORM/ODM 一样,为您提供这些选项:

https://mongoosejs.com/docs/api.html#model_Model.findOne

使用FindOne,您可以搜索文档,但只能返回一个(又名“第一个找到”)文档。 如果需要固定数量的返回文档,可以使用limit(10),例如只返回10个文档。

虽然在我看来,您的 code-sn-ps 没有显示在 Mongoose 中进行查询的确切段,否则我们可以在您自己的示例中向您展示该做什么。

【讨论】:

  • 太棒了,谢谢伙计!这就是我要找的:D
猜你喜欢
  • 2011-05-15
  • 2019-06-15
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2020-09-19
  • 2015-08-19
  • 2020-07-24
  • 2019-11-11
相关资源
最近更新 更多