node.js - 如何在猫鼬中获取最新插入的记录_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
解决方案
- 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
})
推荐阅读
- julia - Julia:接收 Dict 作为输入并输出 Dict 类型的函数是否稳定?
- java - 我的 Flink Streaming 作业执行完成,而数据源仍在产生数据?
- angular - Angular:从 Firestore 获取数据。在单击之前,HTML 不会使用实时数据更新
- google-apps-script - 当单元格有文本时删除行
- vue.js - 当我为我的 v-model 使用动态变量时,它不起作用
- multithreading - 从线程获取连续处理的数据的正确方法是什么?
- react-native - 来自 lottie-react-native 模块的 React Native Android 构建失败
- php - PHP 脚本问题需要 0 个参数,1 个给定 | MYSQL PHP
- kotlin - Kotlin 中有没有办法将变量转换为枚举和接口的交集?
- php - 在 foreach PHP 中显示特定数量的元素