Save only specified field in mongoDB from array of objects

Viewed 28

I want to save only the path field of uploaded documents data.

The function to save the data:

exports.uploadDocuments = async (_id, file) => {
  console.log(Object.values(file.profile_picture));
  if (file.profile_picture) {
    document = await User.findByIdAndUpdate(
      { _id },
      { $set: { profile_picture: Object.values(file.profile_picture) } }
    );
  }
  if (file.documents) {
    document = await User.findByIdAndUpdate(
      { _id },
      {
        $set: { registration_process_value: 99 },
        $push: { documents: { $each: file.documents } },
      },
      { new: true }
    );
  }
  return document;
};

I want to save only profile picture's path but documents I need is full document. How can I save only path field of the document.

The result after I log the files:

[
  {
    fieldname: 'profile_picture',
    originalname: 'Active Drivers.png',
    encoding: '7bit',
    mimetype: 'image/png',
    destination: 'src/uploads/',
    filename: 'profile_picture-1661167606845.png',
    path: 'src\\uploads\\profile_picture-1661167606845.png',
    size: 47922
  }
]
1 Answers

Could you provide your User schema please? Is profile_picture an array or an object?

If it is an object, you can use dot notation to interact with fields from embedded documents:

document = await User.findByIdAndUpdate(
      { _id },
      { $set: { 'profile_picture.path': file.profile_picture.path } }
    );
Related