Javascript 获取NodeJS中Mongo数据库中插入文档的_id
我使用NodeJS在MongoDB中插入文档。使用Javascript 获取NodeJS中Mongo数据库中插入文档的_id,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我使用NodeJS在MongoDB中插入文档。使用collection.insert我可以将文档插入数据库,如下代码所示: // ... collection.insert(objectToInsert, function(err){ if (err) return; // Object inserted successfully. var objectId; // = ??? }); // ... 如何获取插入对象的\u id 有没有办法在不插入最新对象的情况下获取\u i
collection.insert
我可以将文档插入数据库,如下代码所示:
// ...
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId; // = ???
});
// ...
如何获取插入对象的\u id
有没有办法在不插入最新对象的情况下获取\u id
假设同时有很多人访问数据库,我不能确定最新的id是否是插入的对象的id。有第二个参数用于
集合的回调。insert
将返回插入的一个或多个文档,其中应该有_id
尝试:
检查控制台以了解我的意思。比使用第二个参数回调
集合短的方法。insert
将使用objectToInsert.\u id
返回\u id
(在回调函数内部,假设它是一个成功的操作)
NodeJS的Mongo驱动程序将\u id
字段附加到原始对象引用,因此使用原始对象很容易获得插入的id:
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId = objectToInsert._id; // this will return the id of object inserted
});
Mongo将完整的文档作为回调对象发送,因此您只需从那里获取即可 比如说
collection.save(function(err,room){
var newRoomId = room._id;
});
实际上,我为insert回调函数中的第二个参数做了一个console.log()。实际上,除了插入的对象本身之外,还返回了很多信息。下面的代码解释了如何访问它的id
collection.insert(objToInsert, function (err, result){
if(err)console.log(err);
else {
console.log(result["ops"][0]["_id"]);
// The above statement will output the id of the
// inserted object
}
});
现在,您可以在promise的result.insertedId中使用方法和。正如ktretyak所说,要获得插入文档的ID,最好的方法是在result对象上使用insertedId属性。在我的例子中,result.\u id不起作用,因此我必须使用以下命令:
db.collection("collection-name")
.insertOne(document)
.then(result => {
console.log(result.insertedId);
})
.catch(err => {
// handle error
});
如果使用回调,情况也是一样 @JSideris,获取insertedId的示例代码
db.collection(COLLECTION).insertOne(data, (err, result) => {
if (err)
return err;
else
return result.insertedId;
});
如果您想使用“\u id”,请使用simpley
result.insertedId.toString()
//toString将从十六进制转换而来,您可以使用异步函数自动获取_id字段,而无需操作数据对象:
async function save() {
const data = {
name: "John"
}
await db.collection('users').insertOne(data)
return data
}
返回数据:
{
_id: '5dbff150b407cc129ab571ca',
name: 'John'
}
在异步函数中执行此操作的另一种方法:
const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()
// Create.R.U.D
router.post('/new-order', async function (req, res, next) {
// security check
if (Object.keys(req.body).length === 0) {
res.status(404).send({
msg: "Error",
code: 404
});
return;
}
try {
// operations
let orderNumber = await db.collection('orders').countDocuments()
let number = orderNumber + 1
let order = {
number: number,
customer: req.body.customer,
products: req.body.products,
totalProducts: req.body.totalProducts,
totalCost: req.body.totalCost,
type: req.body.type,
time: req.body.time,
date: req.body.date,
timeStamp: Date.now(),
}
if (req.body.direction) {
order.direction = req.body.direction
}
if (req.body.specialRequests) {
order.specialRequests = req.body.specialRequests
}
// Here newOrder will store some informations in result of this process.
// You can find the inserted id and some informations there too.
let newOrder = await db.collection('orders').insertOne({...order})
if (newOrder) {
// MARK: Server response
res.status(201).send({
msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
code: 201
});
} else {
// MARK: Server response
res.status(404).send({
msg: `Order N°${number} not created`,
code: 404
});
}
} catch (e) {
print(e)
return
}
})
// C.Read.U.D
// C.R.Update.D
// C.R.U.Delete
module.exports = router;
与其他响应类似,您可以使用asyncwait、es6+特性获取变量
const insertData=async(数据)=>{
const{ops}=await db.collection('collection').insertOne(数据)
控制台日志(操作[0]。\u id)
}
Callback实际上返回插入的文档数组。因此,如果您插入了单个文档,那么您可以访问插入的记录,如下所示。插入({name:“David”,title:“About MongoDB”},函数(err,records){console.log(“记录添加为”+records[0]。_id);});Ref:Callbacks API已更改:link不提供任何有用的链接我不知道这是通用的还是仅适用于meteor,但当您调用collection.insert(object)时,它会立即返回插入对象的id。docsInserted不会为我返回_id。它为我返回{“ok”:1,“n”:1,“opTime”:{“ts”:“6361004504208375809”,“t”:5},“electionId”:“7FFFFFFF0000000005”}非常有见地的谢谢。自从回调参数更改后,在其他任何地方都找不到此信息。@BradHein不客气!可能MongoDB驱动程序修改了对象引用,因此它在这里也被修改了。:)您的代码是错误的,您说var objectId=objectToInsert.\u id;您的意思是说var objectId=objectInserted.\u id@AndyLorenz插入的对象是什么
?我猜您完全没有领会这个答案的要点:Mongo驱动程序将\u id
字段附加到原始对象。我将答案编辑为在任何地方使用objectToInsert
。希望事情现在更清楚了。:)注意:insert()
不推荐使用。使用insertOne()?这个结果对象来自哪里?@JSideris,正如您在规范方法中看到的,这个方法接受三个参数(doc、options、callback)
。第三个参数-回调,(错误,结果)
。和result
-这就是您要查找的内容。这将输出一个ObjectID{u bsontype:“ObjectID”,id:Buffer(12)}
。如何使用它来获取数据库中的实际id?。。。在另一条评论中找到了答案:使用result.insertedId.toString()
这就是我要找的。谢谢。是的,肯定有版本更改,因为其他答案没有提到结果。insertedId
是一个ObjectID
类型对象.toString()
将此对象转换为真实的UUID。
const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()
// Create.R.U.D
router.post('/new-order', async function (req, res, next) {
// security check
if (Object.keys(req.body).length === 0) {
res.status(404).send({
msg: "Error",
code: 404
});
return;
}
try {
// operations
let orderNumber = await db.collection('orders').countDocuments()
let number = orderNumber + 1
let order = {
number: number,
customer: req.body.customer,
products: req.body.products,
totalProducts: req.body.totalProducts,
totalCost: req.body.totalCost,
type: req.body.type,
time: req.body.time,
date: req.body.date,
timeStamp: Date.now(),
}
if (req.body.direction) {
order.direction = req.body.direction
}
if (req.body.specialRequests) {
order.specialRequests = req.body.specialRequests
}
// Here newOrder will store some informations in result of this process.
// You can find the inserted id and some informations there too.
let newOrder = await db.collection('orders').insertOne({...order})
if (newOrder) {
// MARK: Server response
res.status(201).send({
msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
code: 201
});
} else {
// MARK: Server response
res.status(404).send({
msg: `Order N°${number} not created`,
code: 404
});
}
} catch (e) {
print(e)
return
}
})
// C.Read.U.D
// C.R.Update.D
// C.R.U.Delete
module.exports = router;