簡體   English   中英

無法將對象添加到文檔內的 MongoDB 數組

[英]Can't add object to MongoDB array inside a document

我正在為我的聊天應用程序構建一個 API,我編寫了下面的端點以在 MongoDB 中保存新消息。

消息本身是一個數組。

使用 Postman 測試此端點會在響應中返回新創建的消息,但該消息未添加到我的消息數組中。

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 });
  }
});

這是我的 Mongoose 消息模式:

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);

關於我做錯了什么的任何提示? 非常感謝! :-)

編輯_ 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 文檔.save()已棄用: https : //docs.mongodb.com/manual/reference/method/db.collection.save/

您應該嘗試.update()命令,如$push示例文檔中所示:https : .update()

您的架構和操作有些不匹配。

您正在使用$push用於將數據附加到數組。 您的架構不包含任何數組。

如果您的集合包含作為文檔的消息,那么您應該使用.insertOne代替。

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

newMessage然后將包含創建的文檔。 請注意,此代碼未經測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM