我想从 MongoDB 集合中获取字段中包含用户名或其他名称的所有记录from or to
。这是一个聊天应用程序。我想获取用户和其他用户之间的所有聊天记录。这是一种模式,当用户发送消息时,他们的用户名将保存在from
该部分中,当他们收到消息时,他们的用户名将保存在该to
部分中。对于其他用户来说也是同样的方式。
请参考下面这个:
getMessages: async(_, { name }, context) => {
const user = checkAuth(context);
if(!user) throw new AuthenticationError('Not logged in');
const otherUser = await User.findOne({username: name})
if (!otherUser) throw new UserInputError('User Input Error');
const messages = await Chat.find({
from: otherUser.username || user.username,
to: user.username || otherUser.username
}).sort({createdAt: -1})
return messages
}
关于使用 && 运算符
getMessages: async(_, { name }, context) => {
const user = checkAuth(context);
if (!user) throw new AuthenticationError('Not logged in');
const otherUser = await User.findOne({username: name})
if (!otherUser) throw new UserInputError('User Input Error');
const messages = await Chat.find({ // Here is the change
from: otherUser.username && user.username,
to: user.username && otherUser.username
}).sort({createdAt: -1})
return messages
}
输出
我想获取name
参数中给定用户和登录用户之间的所有记录。例如贾哈德和马齐诺之间。
慕少森
相关分类