I am trying to populate group chat in mongoose and node and I receive the error that populate is not a function.
I use mongoose 5.12.9
Here the chatModel:
const mongoose = require('mongoose');
const chatModel = mongoose.Schema(
{
chatName: { type: String, trim: true },
isGroupChat: { type: Boolean, default: false },
users: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
latestMassage: {
type: mongoose.Schema.Types.ObjectId,
// required: false,
ref: "Message",
},
groupAdmin: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
},
{
timestamps: true,
}
);
const Chat = mongoose.model("Chat", chatModel);
module.exports = Chat;
And then the find that I use:
const asyncHandler = require("express-async-handler");
const Chat = require("../models/chatModel");
// const chatModel = require('../models/chatModel');
const User = require("../models/userModel");
const accessChat = asyncHandler(async (req, res) => {
const { userId } = req.body;
if (!userId) {
console.log("UserId param not sent with request");
return res.sendStatus(400);
}
var isChat = await Chat.find({
isGroupChat: false,
$and: [
{ users: { $elemMatch: { $eq: req.user._id } } },
{ users: { $elemMatch: { $eq: userId } } },
],
})
.populate("users", "-password")
.strictPopulate("latestMessage");
isChat = await User.populate(isChat, {
path: "'latestMessage.sender'",
select: "name pic email",
});
if (isChat.length > 0) {
res.send(isChat[0]);
}
else {
var chatData = {
chatName: "sender",
isGroupChat: false,
users: [req.user._id, userId],
};
try {
const createdChat = await Chat.create(chatData);
const FullChat = await Chat.findOne({ _id: createdChat._id }).populate("users", "-password");
res.status(200).send(FullChat);
} catch (error) {
res.status(400);
throw new Error(error.message);
}
}
});
module.exports = { accessChat, fetchChats, createGroupChat };
It show the chat in postman with post request using token
……………………………………………………
and it show the Error—
“message”: “Chat.find(…).populate(…).strictPopulate is not a function”,
“stack”: “TypeError: Chat.find(…).populate(…).strictPopulate is not a functionn at D:ProjectChatNETbackendcontrollerschatControllers.js:22:10n at asyncUtilWrap (D:ProjectChatNETnode_modulesexpress-async-handlerindex.js:3:20)n at Layer.handle [as handle_request] (D:ProjectChatNETnode_modulesexpresslibrouterlayer.js:95:5)n at next (D:ProjectChatNETnode_modulesexpresslibrouterroute.js:144:13)n at D:ProjectChatNETbackendmiddlewareauthMiddleware.js:18:13n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)”