首页 > 解决方案 > 使用 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

标签: javascriptnode.jsreactjsmongodbmongoose

解决方案


推荐阅读