【发布时间】:2020-04-22 22:21:13
【问题描述】:
在使用 MERN 堆栈构建应用并为用户的items 完成一个简单的 CRUD API 之后,我想向用户模型添加一个“categories”属性然后他可以将其添加到他的项目中......
为了解释这个应用程序,我计划在将他的数据发布到 MongoDB 时,为每个用户附加一些默认数据,即 categories。不幸的是,我未能将这些类别“发布”到数据库中。
这是我尝试过的不同请求和架构组合
- 作为自己的架构
用户路线
const User = require("../models/User")
// @route POST api/users
// @desc Regiter a user
// @access Public
router.post(
"/",
[
check("name", "Please add name")
.not()
.isEmpty(),
check("email", "Please include a valid email").isEmail(),
check(
"password",
"Please enter a password with 6 or more characters"
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
const { name, email, password } = req.body
console.log(categories)
try {
let user = await User.findOne({ email })
if (user) {
return res.status(400).json({ msg: "User already exists" })
}
user = new User({
name,
email,
password,
})
const salt = await bcrypt.genSalt(10)
user.password = await bcrypt.hash(password, salt)
await user.save()
const payload = {
user: {
id: user.id
}
}
jwt.sign(
payload,
config.get("jwtSecret"),
{
expiresIn: 360000
},
(err, token) => {
if (err) throw err
res.json({ token })
}
)
} catch (err) {
console.error(err.message)
res.status(500).send("Server Error")
}
}
)
module.exports = router
AuthState 中的请求
// Register User
const register = async formData => {
console.log(formData)
const expandedFormData = {
...formData,
categories: [
{ name: "Testcategory1", test: 1 },
{ name: "Testcategory2", test: 2 }
]
}
const config = {
headers: {
"Content-Type": "application/json"
}
}
try {
const res = await axios.post("/api/users", expandedFormData, config)
console.log(expandedFormData)
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
loadUser()
} catch (err) {
dispatch({
type: REGISTER_FAIL,
payload: err.response.data.msg
})
}
}
架构
const mongoose = require("mongoose")
const categorieSchema = mongoose.Schema({
label: String,
test: Number
})
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
categories: [categorieSchema]
})
module.exports = mongoose.model("user", UserSchema)
2。 AuthState 中的请求
....
const expandedFormData = {
...formData,
categories: [{ name: "Testcategory1" }, { name: "Testcategory2" }]
}
....
架构
....
categories: [
{
name: String
}
]
....
3。 AuthState 中的请求
架构
与 2 相同。
....
categories: [
{
name: {
type: String
}
}
]
....
4。 请求
架构
与 2 相同。
....
categories: [String]
....
我也阅读了这些主题,但它们没有提供新信息: - Mongoose schema array of objects - Save arrays in Mongoose schema
完整的应用程序可以在https://github.com/mortizw/Repio-2.0查看 除了关于如何使这个模型工作的一些想法之外,我很高兴有一些关于如何迭代测试/接近这种“模式问题”的技巧,就像你可以通过控制台记录一些东西一样。
【问题讨论】:
-
你能把你的后端怎么样
saving users? -
Schema
const categorieSchema = mongoose.Schema({ name: String, test: Number })&&categories: [categorieSchema]应该可以工作,除了categories之外的同一请求中的其他字段是否正在更新?
标签: node.js reactjs mongodb express mongoose