Node.js 如何在mongoose中获取最新插入的记录id
我正在尝试获取最近插入的记录id和p_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: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
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..真的很棒