NodeJS 如何在JavaScript中使用mongoose将item推送到MongoDB中的重嵌套数组

o75abkj4  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(118)

我正在尝试使用expressJS和reactJS构建一个消息站点。我目前正在研究站点的消息发送功能。我的目标是当用户单击react页面上的发送按钮时,它向express后端发出一个post请求,它将消息数据推送到正确的用户“消息”我的MongoDB Altlas集合中的数组。问题是我不知道如何将消息推送到正确的用户数组,因为它与集合中的其他数据嵌套在一起。有人能帮助我吗?
下面是我的index.js express代码,我被卡住了:

const userSchema = new mongoose.Schema({
    name: String,
    password: String,
    profilePicture: String,
    contacts: [{name: String, 
        profilePicture: String, 
        messages: [{sender: String, message: String}], 
    }]
});
const User = new mongoose.model('User', userSchema);

app.post("/send-message", (req, res) => {
    var sender = req.body.sender;
    var recv = req.body.recv;
    var message = req.body.msg
    User.findOne({name: sender}).then(user => {
        user.contacts.forEach(contact => {
            if (contact.name === recv){
                // newMessage is the object I would like to push to the 
                // messages array for the sender.
                var newMessage = {sender: "me", message: message};
            }
        });
    }).then(() => {
        User.findOne({name: recv}).then(user => {
            user.contacts.forEach(contact => {
                if (contact.name === sender){
                    // newMessage is the object I would like to push to 
                    // the messages array for the receiver.
                    var newMessage = {sender: "them", message: message};
                }
            });
        }).then(res.send("Message Sent!"))
        .catch(e => {console.log("2: " + e); res.send("Error!")});
    }).catch(e => {console.log("1: " + e); res.send("Error!")});
});

字符串
下面是我的SendMessage函数的React代码:

const [usrn, setUsrn] = React.useState("<Username>");
const [pass, setPass] = React.useState("<Password>");
const [messageThread, setMessageThread] = React.useState({});
const [message, setMessage] = React.useState("");

const SendMessage = () => {
        axios.post(props.apiUrl + "send-message/", {sender: usrn, recv: 
                   messageThread.contact, msg: message})
        .then(res => {
            console.log(res.data);
            setMessage("");
        });
    }

dwthyt8l

dwthyt8l1#

您可以使用findOneAndUpdate来选择User$push,将新的消息对象添加到正确的数组中。通过选择contacts.name,您可以使用mongodb $位置运算符,它只会推送到匹配的数组元素。
这个例子使用了async/await模式和try/catch来更容易地处理错误。你有多个then.catch块,这在我的经验中是一个向下的螺旋。

app.post("/send-message", async (req, res) => { //< Mark callback as async
    try{
        const sender = req.body.sender;
        const recv = req.body.recv;
        const message = req.body.msg
        // Add message to sender
        const userSender = await User.findOneAndUpdate({ //< use await pattern
            name: sender,
            'contacts.name': recv
        },{
            $push:{
                'contacts.$.messages': { sender: "me", message: message }    
            }
        }, {new: true});
        if(!userSender){ //< If no sender was found return error
            return res.status(400).json({
                message: 'Sender not found'
            })
        }
        // Add message to receiver
        const userReceiver = await User.findOneAndUpdate({ //< use await pattern
            name: recv,
            'contacts.name': sender
        },{
            $push:{
                'contacts.$.messages': { sender: "them", message: message }
            }
        }, {new: true});
        if(!userReceiver){ //< If no receiver was found return error
            return res.status(400).json({
                message: 'Receiver not found'
            })
            // Handle deletion of object in sender
        }
        return res.status(201).json({
            message: 'Messages Saved!'
        })
    }catch(err){
        console.log(err);
        return res.status(500).json({
            message: 'Error on server.'
        })
    }
});

字符串

相关问题