我知道這個問題經常被問到,但我嘗試使用 react-hook-form 和自定義選擇器工具來解決它,所以我沒有發現這種情況。主要目標是將員工收集的資料分配到公司收集。我的模型看起來像這樣(短路):
const companySchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
employees: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Employee',
},
],
}
);
const employeeSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
}
);
我的創建頁面如下所示:
export default function CreateSet() {
const { register, handleSubmit } = useForm();
const router = useRouter();
const { redirect } = router.query;
const { state, dispatch } = useContext(Store);
const { vendorInfo } = state;
useEffect(() => {
if (!vendorInfo) {
router.push('/');
}
}, []);
const submitHandler = async ({
name,
employees: [],
},
}) => {
try {
const { data } = await axios.post(
'/api/company/',
{
name,
employees: [],
},
{
headers: { authorization: `Bearer ${vendorInfo.token}` },
}
);
dispatch({ type: 'COMPANY_CREATE', payload: data });
router.push(redirect || '/vendor/');
} catch (err) {
console.log(getError(err));
}
};
return (
<div title='CompanyCreation' className={styles.register_container}>
<form onSubmit={handleSubmit(submitHandler)}>
<h1>Create Company</h1>
<ul>
<li>
<input
id='name'
label='name'
placeholder='Name'
{...register('name', { required: true })}
/>
</li>
<li>
<p>Employees:</p>
<EmployeeSelector employees={employees} />
</li>
<li>
<button type='submit'>Create</button>
</li>
</ul>
</form>
</div>
);
}
這是 EmployeeSelector 組件:
import React, { useEffect, useReducer, useContext, useState } from 'react';
import axios from 'axios';
import Table from 'react-bootstrap/Table';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import { getError } from '../utils/error';
import { Store } from '../utils/store';
function reducer(state, action) {
switch (action.type) {
case 'FETCH_REQUEST':
return { ...state, loading: true, error: '' };
case 'FETCH_SUCCESS':
return { ...state, loading: false, employees: action.payload, error: '' };
case 'FETCH_FAIL':
return { ...state, loading: false, error: action.payload };
default:
state;
}
}
function EmployeeList() {
const { state } = useContext(Store);
const router = useRouter();
const { vendorInfo } = state;
const [employee, setEmployee] = useState([]);
const [{ loading, error, products }, dispatch] = useReducer(reducer, {
loading: true,
employees: [],
error: '',
});
//selected employees
const selectHandler = (e) => {
e.preventDefault;
e.target.value .....????
};
useEffect(() => {
const fetchData = async () => {
try {
dispatch({ type: 'FETCH_REQUEST' });
const { data } = await axios.get(`/api/employee`, {
headers: { authorization: `Bearer ${vendorInfo.token}` },
});
dispatch({ type: 'FETCH_SUCCESS', payload: data });
} catch (err) {
dispatch({ type: 'FETCH_FAIL', payload: getError(err) });
}
};
fetchData();
}, []);
return (
<div title='EmployeeList'>
{loading ? (
<p>Loading</p>
) : error ? (
<p>{error}</p>
) : (
<Table striped bordered>
<thead>
<tr>
<th>Select</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
{employees.map((employee) => (
<tr key={employee._id}>
<td>
<input
id='employees'
label='employees'
type: checkbox
{...register('employees', { required: true })}
onClick={selectHandler}
/>
</td>
<td>{employee.firstName}</td>
<td>{employee.lastName}</td>
</tr>
))}
</tbody>
</Table>
)}
</div>
);
}
export default dynamic(() => Promise.resolve(EmployeeList), { ssr: false });
所以我試圖實作的是讓用戶可以從串列中選擇一名或多名員工并將他們分配給公司。我不m realy not sure how to make it - my thought was to overgive the values into the state of EmployeeSelector and from there fetch these and fire them into the companys collection. Maybe this is the wrong way, anyway I don知道如何實作這個策略,所以 selectorHandler 看起來像它。有人會告訴我處理這種情況的正確方法來幫助我嗎?謝謝你們!
uj5u.com熱心網友回復:
要將資料從一個分配collection到另一個,您需要創建一個API endpoint(nodejs) -假設您已經創建了 /api/getComplexData.js 檔案
使用此端點,您可以撰寫復雜的“查詢”以從任何集合中獲取任何資料。您在API endpoint. 看看nextjs/mongodb的例子(一,二)
看看復雜的例子,例如$lookup。不要覆寫前端的資料。您可以“合并”、“修改”和洗掉任何型別的資料mongodb queries
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335967.html
