【问题标题】:How can I match all values nested in a collection to values in another collection (mongodb)?如何将嵌套在集合中的所有值与另一个集合(mongodb)中的值匹配?
【发布时间】:2019-07-03 04:45:56
【问题描述】:

我正在创建一个消息传递应用程序,我需要能够显示与给定用户有对话历史记录的用户。 我有用户和对话。型号如下。 (有一个消息集合,其中每个文档都引用一个对话)

//This is the conversation model.
const mongoose = require('mongoose');
const ConversationSchema = new mongoose.Schema({
  participants: {
    type: Array,
    required: true
  }
});
const Conversation = mongoose.model('Conversation', ConversationSchema);

//This is the users model (there's more to it, but this is the relevant stuff)
module.exports = Conversation;
const UserSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  }
});
const User = mongoose.model('User', UserSchema);
module.exports = User;

每个都有一个生成的_id。 我正在发送一个带有用户 ID 的 http 请求。 在我的控制器中,使用猫鼬,我可以执行以下操作:

Conversation.find({participants:req.params.user_id})

这将返回一个对话对象数组,每个对象都包含一个参与者数组(一个用户 ID 数组)。 然后我需要做的是将所有参与者与“用户”集合匹配,这样我就可以获得每个用户的用户 ID、名字和姓氏。

总之,我需要发送一个带有用户 ID 作为参数的 HTTP 请求,并接收一组用户,这些用户与提供的用户有对话历史记录。

下一步是什么?如何将我从相关对话中获得的用户 ID 与用户集合中的用户 ID 匹配?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    试试这个

    app.post('/:user_id', async(req, res) => {
     const partisipant = await Conversation.find({id:req.params.user_id});
     const userData = await User.find({id:req.params.user_id});
     if(!userData || userData != partisipant){
      throw ('no data match')
     }
     //...if found the data, do anything you want
    })
    
    

    使用异步等待从数据库中获取集合数据,并进行比较。

    希望这条线索可以帮助到你

    【讨论】:

    • 我认为为了让这样的事情起作用,我需要将结果作为值(或值数组)而不是作为对象返回。就目前而言,Conversation.find({participants:req.params.user_id}) 返回一个对象数组,其中每个对象都有一个“_id”和“participants”键,参与者值是一个 ID 数组。有没有办法让查询只返回值,而不是整个文档?
    猜你喜欢
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2016-11-26
    相关资源
    最近更新 更多