javascript - 使用 PUT 请求和 updateOne 更新 MongoDB 集合
问题描述
问题:集合中的数据没有更新。我首先尝试做 User.update 和 Group.update 来更新他们的数组,这给了我一个弃用消息,而是做了 updateOne。代码似乎正在运行,但我不明白为什么数据没有更新。我从前端发送的任何内容都会在后端进行处理。后端“auth”是一个JWT令牌验证,通过。我考虑过使用 POST 请求,但我已经有此路由的 POST 请求。
目标:按下“JoinButton”时,更新 Group Schema 中的 'user' 数组,并在当前用户名中 $push
BACKEND EXPRESS ROUTER to "/groups"
router.put("/", auth, async(req, res) => {
try {
await User.updateOne(
{'profile.$.username': req.body.id},
{$addToSet: {'profile.$.groups':req.body.groupId} })
await Group.updateOne(
{name: req.body.groupID},
{$addToSet: {users : req.body.id} })
// below code is just to see if it updated
let user = await User.find({'profile.username': req.body.id})
console.log("user: ", user)
let group = await Group.find({name: req.body.groupId})
console.log("group: ", group)
res.status(200).json({user, group})
} catch {
res.status(500).json({failure:"PUT request failed"})
}
})
GROUP SCHEMA
const mongoose = require("mongoose");
const GroupSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
skills: {
type: String,
required: true
},
description: {
type: String,
required: true
},
curCap: {
type: String,
required: true
},
maxCap: {
type: String,
required: true
},
users: {
type: [String],
required: true
}
})
module.exports = mongoose.model("group", GroupSchema)
USER SCHEMA (in a separate file)
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
profile: {
username: {
type: String,
required: true
},
groups: [String]
},
createdAt: {
type: Date,
default: Date.now()
}
});
module.exports = mongoose.model("user", UserSchema)
FRONTEND FETCH REQUEST
const JoinButton = ({token, id, groupId}) => {
const handleJoin = e => {
e.preventDefault();
if (!token && !id) {
alert("You must log in to join a group")
} else {
fetch ("http://localhost:5000/groups", {
method: "PUT",
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({id, groupId})
})
.then(response => response.json())
.then(data => {
console.log("data", data)
return data
})
.catch(err=>{
console.error("error: ", err)
})
}
}
// return the code for JoinButton component
}
export default JoinButton
解决方案
推荐阅读
- linux - 我正在尝试编写一个 shell 脚本来从文件中读取用户名,但它不起作用。我正在发布我正在编写和输出的脚本
- android - Android,可以在 XML 中添加片段,但不能通过代码
- cmake - Eclipse C/C++ lldb 调试器设置 macOS Catalina
- php - 关于表单提交值未在 php 中插入数据库
- apache-nifi - 安排 NiFi 处理器在收到当天的第一个流文件时运行
- angular - 在 onkeyup 函数期间显示错误
- javascript - 从网页调用 java 方法以生成处理草图并在网页上显示此草图
- twitter-bootstrap - Vee-validate 3 和 Bootstrap 3 表单错误样式
- r - read.table:标题中的百分号 (%) 和正斜杠 (/) 替换为点 (.)
- intellij-idea - Intellij IDEA GIT 注释