gpt4 book ai didi

node.js - 无法将对象添加到文档内的 MongoDB 数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:12 27 4
gpt4 key购买 nike

我正在为我的聊天应用程序构建一个 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 DB Sample

最佳答案

请进行以下更改:

聊天架构文件:

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

关于node.js - 无法将对象添加到文档内的 MongoDB 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59438747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com