我有一个两部分的问题。我试图将数据从本机模式添加到MongoDB。问题的第二部分是,我需要将数据添加到数据库中的用户条目中,每个用户将从该表单中获得附加数据的记录。我不确定该怎么做。这是我第一次使用MongoDB。
我使用了与创建用户相同的结构,但是当我提交表单数据时,什么也没有发生。
包装明细表
import React, { Component } from "react";
import {
Modal,
Picker,
View,
Image,
Text,
TextInput,
StyleSheet,
Button
} from "react-native";
import { Input, CheckBox, Divider } from "react-native-elements";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import axios from "axios";
import baseUrl from "../baseUrl";
axios.defaults.baseURL = baseUrl;
export default class DisplayModal extends Component {
constructor(props) {
super(props);
this.state = {
display: false,
recipient_name: "",
weight: "",
fragile: false,
urgent: false,
additional: ""
};
}
setModalVisible() {
this.setState(prevState => ({ display: !prevState.display }));
}
setStateUtil = (property, value = undefined) => {
this.setState({
[property]: value
});
};
async handlePackage() {
try {
const {
recipient_name,
weight,
fragile,
urgent,
additional
} = this.state;
await axios.post("/package", {
recipient_name,
weight,
fragile,
urgent,
additional
});
} catch (error) {
this.setState({ errorMessage: error.response.data.message });
}
}
render() {
const props = this.props;
return (
<Modal
visible={this.props.display}
animationType="slide"
onRequestClose={() => console.log("closed")}
recipient_name={this.state.recipient_name}
fragile={this.state.fragile}
urgent={this.state.urgent}
additional={this.state.additional}
>
<View style={styles.container}>
<KeyboardAwareScrollView>
<View>
<Input
placeholder="Recipient Name"
autoCapitalize="none"
autoCorrect={false}
value={this.state.recipient_name}
onChangeText={changedRecipientName =>
this.setStateUtil("recipient_name", changedRecipientName)
}
/>
<View style={{ flexDirection: "row" }}>
<Text style={styles.heading}>Package Weight</Text>
<Picker
selectedValue={this.state.language}
style={{
height: 50,
width: 130,
marginLeft: 20,
marginTop: 11
}}
onValueChange={(itemValue, itemIndex) =>
this.setState({ language: itemValue })
}
value={this.state.weight}
onChangeText={weight =>
this.state.handleChange("weight", weight)
}
>
<Picker.Item label="1-5kg" value="one" />
<Picker.Item label="6-10kg" value="six" />
<Picker.Item label="10-20kg" value="ten" />
</Picker>
</View>
<CheckBox
title="Fragile"
onPress={() =>
this.setState({
fragile: !this.state.fragile
})
}
checked={this.state.fragile}
value={this.state.fragile}
onChangeText={fragile =>
this.state.handleChange("fragile", fragile)
}
/>
<CheckBox
onPress={() =>
this.setState({
urgent: !this.state.urgent
})
}
title="Urgent"
checked={this.state.urgent}
value={this.state.urgent}
/>
<Text style={styles.headingInfo}>Additional Info</Text>
<TextInput
style={{
height: 180,
marginLeft: 18,
marginRight: 18,
marginBottom: 18,
textAlignVertical: "top",
borderWidth: 0.3,
padding: 10
}}
placeholder="Please add any additional info"
value={this.state.additional}
onChangeText={changedAdditional =>
this.setStateUtil("additional", changedAdditional)
}
/>
<View style={{ height: 60 }} />
</View>
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "center"
}}
>
<View style={{ flex: 1, margin: 18 }}>
<Button
onPress={() => {
this.props.triggerModal();
}}
title="Continue"
color="green"
/>
</View>
<View style={{ flex: 1, margin: 18 }}>
<Button
onPress={() => {
this.handlePackage();
this.props.triggerModal();
}}
title="Cancel"
color="red"
/>
</View>
</View>
</KeyboardAwareScrollView>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff"
},
heading: {
fontSize: 23,
paddingLeft: 20,
marginTop: 20,
marginBottom: 20
},
headingInfo: {
fontSize: 23,
paddingLeft: 20,
marginTop: 20,
marginBottom: 20
},
buttonContinue: {
marginBottom: 30
}
});
controllers / package.js
const Package = require("../model/Package");
exports.getPackages = async (req, res, next) => {
try {
const packageFromDb = await Package.find({});
const package = packageFromDb.map(
({
recipientName,
Package_Weight,
Fragile,
Urgent,
Additional_Note
}) => ({
recipientName,
Package_Weight,
Fragile,
Urgent,
Additional_Note
})
);
return res.json({ package });
} catch (err) {
next(err);
}
};
model / Package.js
const mongoose = require("mongoose");
const packageSchema = new mongoose.Schema({
recipientName: {
type: String,
required: true
},
package_Weight: {
type: String,
required: true
},
fragile: {
type: Boolean,
required: true
},
urgent: {
type: Boolean,
required: true
},
additional_Note: {
type: String,
required: true
}
});
const Package = mongoose.model("Package", packageSchema);
module.exports = Package;
routes / package.js
const express = require("express");
const packageController = require("../controllers/package");
const router = express.Router();
router.get("/", packageController.getPackages);
module.exports = router;
index.js
const express = require("express");
const bodyParser = require("body-parser");
const mongoDbConnectionString = require("./config/mongodb");
const mongoose = require("mongoose");
const authRouter = require("./routes/auth");
const userRouter = require("./routes/users");
const packageRouter = require("./routes/package");
const authMiddleware = require("./middleware/auth");
const errorMiddleware = require("./middleware/error");
const PORT = 4000;
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/auth", authRouter);
app.use("*", authMiddleware);
app.use("/users", userRouter);
app.use("/package", packageRouter);
app.use(errorMiddleware);
mongoose
.connect(
mongoDbConnectionString,
{ useNewUrlParser: true }
)
.then(result => {
console.log("Connected to Mongodb");
app.listen(PORT, () => {
console.log("Server is listening on PORT: " + PORT);
});
})
.catch(err => {
console.error(err);
});
controllers / auth.js
const User = require("../model/User");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const jwtSecret = require("../config/jwtSecret");
exports.loginUser = async (req, res, next) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user) {
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (isPasswordCorrect) {
const token = jwt.sign({ email: user.email }, jwtSecret);
return res.json({ token });
}
const error = new Error(`Password does not match email ${email}`);
error.statusCode = 401;
throw error;
}
const error = new Error(`This email ${email} does not exist`);
error.statusCode = 401;
throw error;
} catch (err) {
next(err);
}
};
exports.createUser = async (req, res, next) => {
try {
const { firstName, lastName, email, password } = req.body;
if (await User.findOne({ email })) {
const error = new Error(
`An account with the mail ${email} already exists`
);
error.statusCode = 409;
throw error;
}
const hashedPassword = await bcrypt.hash(password, 12);
const user = new User({
firstName,
lastName,
email,
password: hashedPassword
});
const result = await user.save();
res.send(result);
} catch (err) {
next(err);
}
};
middleware / auth.js
const jwt = require("jsonwebtoken");
const jwtSecret = require("../config/jwtSecret");
module.exports = (req, res, next) => {
const authHeader = req.get("Authorization");
if (!authHeader) {
const error = new Error("Authorization header missing token");
error.statusCode = 401;
throw error;
}
try {
const token = authHeader.split(" ")[1];
const decodedToken = jwt.verify(token, jwtSecret);
} catch (err) {
err.statusCode = 401;
throw err;
}
next();
};
controllers / users.js
const User = require("../model/User");
exports.getUsers = async (req, res, next) => {
try {
const usersFromDb = await User.find({});
const users = usersFromDb.map(({ firstName, lastName, email }) => ({
firstName,
lastName,
email
}));
return res.json({ users });
} catch (err) {
next(err);
}
};
我希望将数据添加到数据库的方式与添加用户(正确添加用户)的方式相同。缺少的代码将允许将包数据添加到添加详细信息的每个用户,但是我不确定如何做到这一点。