Skip to content

Instantly share code, notes, and snippets.

@19sajib
Created June 30, 2022 12:45
Show Gist options
  • Save 19sajib/347e9666972c8b61b44991bb3686b9ae to your computer and use it in GitHub Desktop.
Save 19sajib/347e9666972c8b61b44991bb3686b9ae to your computer and use it in GitHub Desktop.
Common MongoDB Query

MongoDB

// Connecting to mongoDB mongoose.connect(CONNECTION_URL,

{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, },

(err) => { if(err) return console.error(err); console.log("Connected to MongoDB") })

//find specific user by user_id, username await UserModel.findOne({user._id//username}) await UserModel.findById(id) const chat = await ChatModel.findOne({ members: {$all: [req.params.firstId, req.params.secondId]} }) const chat = await ChatModel.find({ members: {$in: [req.params.userId]} })

////Get all user info without password let users = await UserModel.find();

users = users.map((user)=>{
  const {password, ...otherDetails} = user._doc;
  return otherDetails;
})

//update a user with specific id await UserModel.findByIdAndUpdate(id, req.body/updated_body, { new: true, }) const post = await PostModel.findById(postId); await post.updateOne({ $set: req.body } await Admin.findOneAndUpdate({ _id: process.env.Admin_Id }, { $set: traficData//Object }, { new: true }) await Admin.findOneAndUpdate({ _id: process.env.Admin_Id }, { $inc: { totalHelp: 1 }}, { new: true })

//delete a user with specific id await UserModel.findByIdAndDelete(id) const post = await PostModel.findById(postId); await post.deleteOne() await PostMessage.findByIdAndRemove(id);

//push something on a user's property array with specific id const followUser = await UserModel.findById(id) await followUser.updateOne({$push : {followers: _id_want_to_push}})

//pull something on a user's property array with specific id const followUser = await UserModel.findById(id) await followUser.updateOne({$pull : {followers: _id_want_to_pull}})

//sort data after fetching await Verification.find({isSolved: false}).sort({createdAt: 1})

// timeline post const currentUserPosts = await PostModel.find({userId}); const followingPosts = await UserModel.aggregate([ { $match: { _id: new mongoose.Types.ObjectId(userId) } },
{ $lookup: { from : "posts", localField: "following", foreignField: "userId", as: "followingPosts" } }, { $project: { followingPosts: 1, _id: 0 } } ])

    res.status(200)
       .json(currentUserPosts
        .concat(...followingPosts[0].followingPosts)
        .sort((a,b)=> {
            return b.createdAt - a.createdAt
        })
        )

//fetching post according to pagination const getPosts = async (req, res) => {

const { page } = req.query;

try {
    const LIMIT = 6;
    const startIndex = (Number(page) - 1) * LIMIT; // get the starting index of every page

    const total = await PostMessage.countDocuments({hideAfter: { $gt:Date.now()}});
    const posts =await PostMessage.find({hideAfter: { $gt:Date.now()}}).sort({hideAfter: 1}).limit(LIMIT).skip(startIndex);

    res.json({ data: posts, currentPage: Number(page), numberOfPages: Math.ceil(total / LIMIT)});
} catch (error) {
   res.status(400).json({ message: error.message}) 
} 

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment