无法将对象添加到文档内的MongoDB数组 [英] Can't add object to MongoDB array inside a document

查看:81
本文介绍了无法将对象添加到文档内的MongoDB数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的聊天应用程序构建API,并在下面编写了端点以将新消息保存在MongoDB中.

I'm building an API for my chat application and I wrote the endpoint below to save new messages in MongoDB.

消息本身是一个数组.

The messages themselves are an array.

使用Postman测试此端点将在响应中返回新创建的消息,但该消息未添加到我的消息数组中.

Testing this endpoint with Postman returns the newly created message in the response but the message is not added to my array of messages.

router.post('/:id/messages', async (request, response) => {
  const chatMessage = new Message({
    type: request.body.type,
    body: request.body.body,
    author: request.body.author
  });
  try {
    const newMessage = await chatMessage.save({ $push: { chatMessage } });
    response.status(201).json(newMessage);
  } catch (error) {
    response.status(400).json({ message: error.message });
  }
});

这是我的猫鼬模式,用于消息:

Here's my Mongoose schema for messages:

const mongoose = require('mongoose');

const messageSchema = new mongoose.Schema({
  type: {
    type: String
  },
  body: {
    type: String
  },
  author: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Message', messageSchema);

关于我做错了什么的任何提示吗? 太感谢了! :-)

Any hints on what I've done wrong? Thank you so much! :-)

EDIT_ Mongo数据库示例

推荐答案

请进行以下更改:

聊天架构文件:

/** messages schema w.r.t. messages field in chat document */
const messageSchema = new mongoose.Schema({
    type: {
        type: String
    },
    body: {
        type: String
    },
    author: {
        type: String
    },
    date: {
        type: Date,
        default: Date.now
    }
});

/** Actual chat schema */
const chatsSchema = new mongoose.Schema({
    id: Number,
    user1: String,
    user2: String,
    messages: [messageSchema]
});

function getChatsModel() {
    if (mongoose.models && mongoose.models.chats) {
        return mongoose.models.chats;
    }
    return mongoose.model('chats', chatsSchema, 'chats');
}

module.exports = getChatsModel();

代码:

/** Import chats model file here & also do require mongoose */
router.post('/:id/messages', async (request, response) => {
    const chatMessage = {
        messages: {
            type: request.body.type,
            body: request.body.body,
            author: request.body.author
        }
    };
    try {
        const id = mongoose.Types.ObjectId(request.params.id);
        const dbResp = await Chats.findOneAndUpdate({ "_id": id }, { $push: chatMessage }, { new: true }).lean(true);
        if (dbResp) {
            // dbResp will be entire updated document, we're just returning newly added message which is input.
            response.status(201).json(chatMessage);
        } else {
            response.status(400).json({ message: 'Not able to update messages' });
        }
    } catch (error) {
        response.status(500).json({ message: error.message });
    }
});

这篇关于无法将对象添加到文档内的MongoDB数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆