Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在mongoose中获取最新插入的记录id_Node.js_Mongoose_Mongoose Web Server - Fatal编程技术网

Node.js 如何在mongoose中获取最新插入的记录id

Node.js 如何在mongoose中获取最新插入的记录id,node.js,mongoose,mongoose-web-server,Node.js,Mongoose,Mongoose Web Server,我正在尝试获取最近插入的记录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:5eba58f0e5d

我正在尝试获取最近插入的记录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
  • MongoDB本机不支持增量自动生成的数字,因此在第一种情况下,如果不单独管理计数器,就不可能实现。您可以计算文档数,但不能计算已删除的文档数
  • 对于第二种情况,您几乎得到了:
  • 使用异步/等待

    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
    })
    
    没有异步/等待

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

    获取错误:SyntaxError:await仅在异步函数中有效我在answerp_id值中添加了另一个选项获取null wow..真的很棒