const Contact = require('./schemas/contact'); const getList = async ( options, { sortBy, sortByDesc, filter, limit = '500', page = '1', sub } ) => { if (sub) options.subscription = { $all: [sub] }; const results = await Contact.paginate(options, { limit, page, sort: { ...(sortBy ? { [`${sortBy}`]: 1 } : {}), ...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}), }, select: filter ? filter.split('|').join(' ') : '', populate: { path: 'owner', select: '_id', }, }); const { docs: contacts, totalDocs: total } = results; return { total: total.toString(), limit, page, contacts }; }; const getById = async (id, userId) => { const foundContact = await Contact.findById({ _id: id, owner: userId, }); return foundContact; }; const getByField = async (number, userId) => { const contact = await Contact.findOne({ number, owner: userId, }); return contact; }; const add = async (obj) => { const contact = await Contact.create(obj); return contact; }; const remove = async (id, userId) => { const removedContact = await Contact.findByIdAndRemove({ _id: id, owner: userId, }); return removedContact; }; const update = async (id, userId, body) => { return await Contact.findByIdAndUpdate( { _id: id, owner: userId }, { ...body }, { new: true } ); }; const updateCompanionsContact = async (number, obj) => { const contacts = await Contact.updateMany({ number }, { ...obj }); return contacts; }; module.exports = { getList, getByField, getById, add, remove, update, updateCompanionsContact, };