Home > Mobile >  change mongodb 'payments._id' to a timestamp
change mongodb 'payments._id' to a timestamp

Time:01-04

Please change the value of 'payments._id' to a timestamp. The 'payments._id' object is created by MongoDB when inserting a document into the collection.

onMounted(async () => {
  const res = await axios.get("http://127.0.0.1:49146/server/po_payment");
  payments.value = res.data; 

I'm trying to convert the _id field of a document in a MongoDB collection to a timestamp. I've tried using getTimestamp(), but it does not work. I've seen that it works in the MongoDB shell, but I'm not sure if it can only be used there. I've searched online but I'm still not sure how to do this. Can you suggest a solution?"

onMounted(async () => {
  const res = await axios.get("http://127.0.0.1:49146/server/po_payment");
  payments.value = res.data; 
  payments.value.forEach(payment => {
    payment.timestamp = new ObjectId(payment._id).getTimestamp();
  });

CodePudding user response:

function objectIdToTimestamp(objectId) {
    return parseInt(objectId.substring(0, 8), 16);
};

MongoDB uses the first 8 characters to store the timestamp as hexadecimal. You can easily extract that with the function here.

  • Related