猿问

MongoDB无法获取所有数据

问题

我想从 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

}

输出

https://img.mukewang.com/64cdbca60001276212350478.jpg

客观的

我想获取name参数中给定用户和登录用户之间的所有记录。例如贾哈德和马齐诺之间。


繁星点点滴滴
浏览 117回答 1
1回答

慕少森

只需尝试使用$or运算符,例如:const messages = await Chat.find({            from: {$or: [otherUser.username, user.username]},    to: {$or: [otherUser.username, user.username]}}).sort({createdAt: -1})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答