Node.js 构建查询以获取sails js中的聊天对话消息
假设我有下面描述的模型模式,以便在我的sails应用程序中添加两个用户之间的聊天功能。例如,如果我让用户A向用户B发送消息,那么用户B将回复用户A,这将始终在两个用户之间创建两个对话。所以我的问题是如何查询两个对话以从A和B获得消息。我尝试了类似的方法,但可能有一个简单的逻辑Node.js 构建查询以获取sails js中的聊天对话消息,node.js,sails.js,waterline,Node.js,Sails.js,Waterline,假设我有下面描述的模型模式,以便在我的sails应用程序中添加两个用户之间的聊天功能。例如,如果我让用户A向用户B发送消息,那么用户B将回复用户A,这将始终在两个用户之间创建两个对话。所以我的问题是如何查询两个对话以从A和B获得消息。我尝试了类似的方法,但可能有一个简单的逻辑 // User Model attributes: { username: { type: 'string', required: true, unique: true, },
// User Model
attributes: {
username: {
type: 'string',
required: true,
unique: true,
},
conversations_sender: {
collection: conversation,
via: 'sender'
},
conversations_recipient: {
collection: conversation,
via: 'recipient'
}
}
// Conversation model
attributes: {
sender: {
model: user
},
recipient: {
model: user
},
messages: {
collection: 'message',
via: 'conversation'
}
}
// Message model
attributes: {
text: {
type: 'string'
},
conversation: {
model: 'conversation'
},
}
// Conversation Controller
get: function(req, res) {
var params = {
or : [
{
sender: req.param('sender'),
recipient: req.param('recipient')
},
{
sender: req.param('recipient'),
recipient: req.param('sender')
}
]
}
Conversation.find(params) ...
}
您应该重新考虑一下您的模式,请参阅此链接,该链接具有适合您需要的良好数据库设计: 然后,您应该能够使用如下2个用户ID获取所有消息:
Conversation.findAll({sender: ..., receiver: ...})
此外,您还需要消息的时间戳,将来您将希望以某种方式对消息进行排序,并使良好的“Read Day”功能createdAt和updatedAt字段由Sails在每个模型上自动创建。如果您使用生成器,但在他的代码中没有任何创建和更新的字段