我怎样才能匹配嵌套一个集合中值的另一个集合(MongoDB的)所有值?
我创建一个消息传递应用程序,我需要能够显示与特定用户会话历史记录的用户。我有用户和对话。该机型如下。 (有一个消息集合,其中每个文档是指会话)
//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得到什么?
回答如下:这种尝试
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
})
使用异步等待从数据库中获取的数据收集,并进行比较。
希望这条线索可以帮助你