0

I am trying to query documents based on particular date range. So I need all the documents where the createdDate is less than equal to current date and greater than equal to currentDate - 2. I am assuming that there is some issue in the date format between how mongo db stores and how I am trying to fire that in the query. Attached the screenshot. Can someone please help

getMessagesController.js

export const getMessages = async (req, res) => {
  const currentUserId = req.user._id;
  const activeScreenUserId = req.params.id;
  const daysRange = parseInt(req.params.daysRange);

  const currentDate = new Date();
  const currentDateUTC = new Date(currentDate.toISOString());

  // Calculate the date 2 days ago in UTC
  const previousDate = new Date(currentDate);
  previousDate.setUTCDate(currentDate.getUTCDate() - daysRange);
  const previousDateUTC = new Date(previousDate.toISOString());

  const conversation = await Conversation.findOne({
    participants: { $all: [currentUserId, activeScreenUserId] },
  });

  if (!conversation) {
    return res.status(200).json({
      messages: [],
    });
  }

  const messages = await Message.find({
    conversationId: conversation._id,
    createdDate: {
      $gte: previousDateUTC,
      $lte: currentDateUTC,
    },
  });
  //   const messages = conversation.messages.map((message) => {
  //     return message;
  //   });
  res.status(200).json({
    messages,
  });
};

message.model.js

import mongoose from "mongoose";

const messageSchema = new mongoose.Schema(
  {
    conversationId: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: "Conversation",
    },
    senderId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    receiverId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    message: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

const Message = mongoose.model("Message", messageSchema);

export default Message;

enter image description here

5
  • 1
    Do not post image please. Commented Jul 16, 2024 at 7:20
  • 1
    Share your code and document as code snippet instead of images. Commented Jul 16, 2024 at 8:27
  • I have edited the question with the actual code snippet. Can you please take a look Commented Jul 16, 2024 at 11:54
  • care to share more details on how you're unable to see the results? Commented Jul 16, 2024 at 12:22
  • Even if I am having the record in mongodb database, I am getting empty array. Commented Jul 16, 2024 at 13:26

1 Answer 1

1

Your field is named createdAt not createdDate. Try this simplified implementation:

const currentDate = new Date();
let previousDate = new Date(currentDate);
previousDate.setDate(currentDate.getDate() - daysRange);

const messages = await Message.find({
    conversationId: conversation._id,
    createdAt: {
        $gte: previousDate,
        $lte: currentDate,
    }
})
Sign up to request clarification or add additional context in comments.

1 Comment

OMG, I didnt notice I am using a different name. Thanks @jQueeny for observing that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.