export const movepoint = async (req, res) => {
const { fromindex, toindex } = req.body;
console.log("Came to backend:", fromindex, toindex);
try {
if (fromindex === toindex) {
return res.status(200).json("Properties fromindex and toindex are the same");
}
let docToMove = await Point.findOne({ index: fromindex });
console.log("DocToMove:",docToMove)
if (!docToMove) {
return res.status(404).json("Point not found");
}
if (fromindex < toindex) {
await Point.updateMany(
{ index: { $gt: fromindex, $lte: toindex } },
{ $inc: { index: -1 } }
);
} else {
await Point.updateMany(
{ index: { $lt: fromindex, $gte: toindex } },
{ $inc: { index: 1 } }
);
}
const doume = await Point.updateOne({ _id: docToMove._id }, { $set: { index: toindex } })
const sortedDocs = await Point.find({}).sort({ index: 1 });
console.log("Sorted Docs:", sortedDocs);
return res.status(200).json("Successfully moved point");
} catch (err) {
console.error(err);
return res.status(500).json({ error: 'Internal Server Error' });
}
};
This my code.Everything is ok but the end is sorting the collection array by index.why?Answers really appricieted!!!