簡體   English   中英

如何使用反應從 Mongodb 集合中查詢單個文檔

[英]How to query a single document from a Mongodb collection with react

我正在嘗試構建一個帶有 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;

使用貓鼬的 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,然后把我的集合中存儲的所有數據拉下來,這里是返回數據的圖像。

前端顯示的數據

圖片

但是我想知道是否可以只下拉該集合中的一個文檔,因此它只會顯示一個 Name: 然后是其他 4 位數據。

我將數據存儲在 Mlab 中,這是存儲在我的集合中的文檔的屏幕截圖。

mongodb中的數據圖片

這可能嗎? 謝謝!

最好的方法是僅從數據庫中提取一個文檔(如果您不需要更多文檔)。

Mongoose 與任何其他 ORM/ODM 一樣,為您提供以下選項:

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

使用FindOne您可以搜索文檔,但只能返回一個(也稱為“第一個找到的”)文檔。 如果您需要固定數量的返回文檔,則可以使用limit(10)來例如僅返回 10 個文檔。

雖然在我看來您的代碼片段沒有顯示在 Mongoose 中進行查詢的確切部分,否則我們可以在您自己的示例中向您展示要做什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM