node.jsmongoosemongoose-web-server

How to get lastest inserted record _id in mongoose


I am trying to get recently inserted record _id and p_id but i do not know how to get the value.Below given my code.This is not working.How to do it?

DB records:

{
_id:5eba58f0e5def333ad4d8c8d,
p_id:"C1",
product_name:"Name",
product_weight:123
},
{
_id:5eba58f0e5def333ad4d8c8e,
p_id:"C2",
product_name:"Name",
product_weight:123
},
{
_id:5eba58f0e5def333ad4d8c8f,
p_id:"C3",
product_name:"Name",
product_weight:123
}

data.controller.js:

var Product = mongoose.model(collectionName);

 let latest_id = Product.findOne().sort({ field: 'asc', _id: -1 }).limit(1);

 console.log("_id" + val);  //output should be 3 

 let latest_p_id = Product.findOne().sort({ field: 'asc', p_id: -1 }).limit(1);

 console.log("p_id" + val);  //output should be C3

Solution

    1. MongoDB does not natively support incremental auto generated numbers, so your first case, it's not possible if you don't manage your counter separately. You can count the number of documents, but it won't account for deleted documents.
    2. For the second case, you almost got it:

    with async/await

    const product = await Product.findOne().sort({ p_id: -1 }).limit(1)
    console.log(product.p_id) // this will be your desired output
    

    without async/await

    Product.findOne().sort({ p_id: -1 }).limit(1).then((product) => {
      console.log(product.p_id) // this will be your desired output
    })