簡體   English   中英

如何在 mongoose 中獲取最新插入的記錄 _id

[英]How to get lastest inserted record _id in mongoose

我正在嘗試獲取最近插入的記錄 _id 和 p_id 但我不知道如何獲取值。下面給出我的代碼。這不起作用。怎么做?

數據庫記錄:

{
_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
}

數據.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
  1. MongoDB 本身不支持增量自動生成的數字,所以你的第一種情況,如果你不單獨管理你的計數器是不可能的。 您可以計算文檔的數量,但它不會計算已刪除的文檔。
  2. 對於第二種情況,你幾乎明白了:

使用異步/等待

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

沒有異步/等待

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM