node.js - 在 mongoose 中保存和检索相关数据
问题描述
我正在 node.js、socket.io 和 mongoDB 中构建一个消息传递系统。我很了解 node.js 和 socket.io,但我是 mongoDB 的新手。这是我到目前为止的猫鼬模式:
对话模型.js:
const mongoose = require('mongoose');
const conversationSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
created_at: {type: Date, default: Date.now}
});
module.exports = mongoose.model('Conversation', conversationSchema);
在 message_model.js 我有:
const mongoose = require('mongoose');
const messageSchema = new mongoose.Schema({
message: String,
conversation_id: String,
user_id: Number
});
module.exports = mongoose.model('Message', messageSchema);
我的对话是在单独的快速路线中创建的,有时当用户添加消息时,我会像这样保存新消息:
MessageModel.create(
{
conversation_id: data.conversation_id,
message: data.message,
user_id: data.user_id
}
).then((response) => {
callback(response);
}).catch(err => console.error(err));
该消息也保存在其相关集合中。但是现在我想在猫鼬查找操作中检索对话及其所有消息。
我已经阅读了关于猫鼬填充并在对话模型中创建消息的引用,但是当我查询时,我没有在对话中添加消息。
这是我的查找电话:
ConversationModel.findById(conversation_id).populate('messages').then(conversationDetail => {
console.log(conversationDetail);
}).catch(err => console.error(err));
这是我更新的对话模型,用于获取消息以及对话查找操作:
const mongoose = require('mongoose');
const conversationSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
created_at: {type: Date, default: Date.now},
messages :[{type: mongoose.Schema.Types.ObjectId, ref: 'Message' }]
});
module.exports = mongoose.model('Conversation', conversationSchema);
但它不起作用。即使存在与该对话相关的消息,对话查找操作也始终使消息数组为空。
另外请告诉我在消息模型中保存会话 ID 字段是个好主意吗?谢谢
解决方案
您缺少消息模型上的反向链接。因此,如果您想在该集合中使用 refs,那么您真的别无选择将 conversation_id 放在那里。将其视为 SQL 中的外键关系。
conversation_id: String,
应该:
conversation_id: {type: mongoose.Schema.Types.ObjectId, ref: "Conversation", index: true}
推荐阅读
- python - 编译 TensorFlow 模型时定义 BLEU
- java - 如何在没有切换案例的情况下从 json 列表中实例化一组不同的对象?
- javascript - 完整日历 v5。做出反应。如何添加自定义列
- websphere - C9510-401 IBM WAS Network Deployment V8.5.5 和 Liberty Profile 认证
- r - ggplot2 for-loop 设置预定的不透明度
- javascript - 通过 XMLHttpRequest (API) 在 HTML 表上显示请求结果
- kubernetes - K8s 中针对 Pod 失败的警报
- javascript - 如何在反应中按百分比滚动?
- spring - 春季启动上下文创建错误,以防在春季 Redis 集群配置中无法访问一个主节点
- c++ - 如何使用 nlohmann json 解析对象数组?