Home > Mobile >  Save only required data in MongoDB and node.js
Save only required data in MongoDB and node.js

Time:07-24

I want to store only username in the mentions array pointing to the user from the same collection but it is saving all data of mentioned user in MongoDB like following:

{
    "userId": "62db90256a7a0d1b38ee15b5",
    "media": [
        "nothing"
    ],
    "mentions": [
        {
            "_id": "62db797c0d2bdc605e6d1810",
            "Name": "Mitul Kheni",
            "email": "[email protected]",
            "User_name": "Mitul_kheni",
            "phoneNumber": "1234567890",
            "password": "$2a$08$pb6Nu8MlIX7.L0S8vBP6NOFxjc9rZCXOUFA9.IsMBwkENmap946yO",
            "gender": "male",
            "followers": [],
            "following": [],
            "BlockedUser": [],
            "profileStatus": "public",
            "Like": [],
            "disLike": [],
            "tokens": [
                {
                    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MmRiNzk3YzBkMmJkYzYwNWU2ZDE4MTAiLCJpYXQiOjE2NTg1NTA2NTIsImV4cCI6MTY1ODYzNzA1Mn0.128eZ80OjCxMEk3A_mRpInR1ZP4L-YdgTS2JBQUJjxs",
                    "_id": "62db797c0d2bdc605e6d1812"
                }
            ],
        },

It is saving all the users that are stored into a database in the mentions array like above even if I haven't mentioned that user.

the query to create a new post:

exports.createPost = async (req, res) => {
  try {
    const user = await User.findById(req.user._id);
    if (!user) return res.status(401).json({ message: "No user found" });
    const { media, hashTags, postStatus } = req.body;

    const mentions = await User.find({ User_Name: req.body.User_Name });
    if (!mentions) {
      return res.status(404).send("Please enter valid user name");
    }

    let new_post = new Post({
      userId: req.user._id,
      media,
      mentions,
      hashTags,
      postStatus,
    });
    const post = await new_post.save();
    return res.status(200).send(post);
  } catch (error) {
    return res.status(500).send(error.message);
  }
};

The user_name schema from post table:

mentions: {
      type: Array,
      default: [],
    },

How can I restrict this to save only username and only mentioned username?

CodePudding user response:

The problem is here:

    let new_post = new Post({
      userId: req.user._id,
      media,
      mentions,
      hashTags,
      postStatus,
    });  

You are directly passing the mentions obtained from mongodb while creating a Post object. Instead, you should map it to only save username. Like this:

    let new_post = new Post({
      userId: req.user._id,
      media,
      mentions: mentions.map(user => {User_name: user.User_name}),
      hashTags,
      postStatus,
    }); 

Or you can project, only User_name from your query like this:

const mentions = await User.find({ User_Name: req.body.User_Name }, {User_name: 1, _id: 0});

UPDATE

We were searching by wrong key, it should be User_name, not User_Name, try this:

const mentions = await User.find({ User_name: req.body.User_Name }, {User_name: 1, _id: 0});

Also check, what is the exact key, present in the request body. To check for an empty array, apply the following condition:

if (req.body.mentions && (!Array.isArray(mentions) || mentions.length === 0)) {
  return res.status(404).send("Please enter valid user name");
}
let postBody = {
  userId: req.user._id,
  media,
  hashTags,
  postStatus,
};
if(mentions.length > 0) {
  postBody = {...postBody, mentions};
}
let new_post = new Post(postBody);
  • Related