首页 > 解决方案 > 如何在猫鼬中获取最新插入的记录_id

问题描述

我正在尝试获取最近插入的记录 _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
}

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

标签: node.jsmongoosemongoose-web-server

解决方案


  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
})

推荐阅读