javascript 使用PUT请求和updateOne更新MongoDB集合

svgewumm  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(141)

问题:集合中的数据未更新。我首先尝试使用User.update和Group.update来更新它们的数组,这给了我一个弃用消息,然后使用updateOne来代替。代码似乎正在运行,但我不明白为什么数据没有更新。我从前端发送的任何内容都在后端处理。后端“auth”是一个JWT令牌验证,它通过了。我考虑过使用POST请求,但我已经有了这个路由的POST请求。
目标:当按下“JoinButton”时,更新GroupSchema中的'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
xjreopfe

xjreopfe1#

使用FindONeandUpdate()代替upadateOne()

相关问题