首页 > 解决方案 > 在 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 字段是个好主意吗?谢谢

标签: node.jsmongodbmongoosenosql

解决方案


您缺少消息模型上的反向链接。因此,如果您想在该集合中使用 refs,那么您真的别无选择将 conversation_id 放在那里。将其视为 SQL 中的外键关系。

conversation_id: String,

应该:

conversation_id: {type: mongoose.Schema.Types.ObjectId, ref: "Conversation", index: true}

推荐阅读