Ion*_*zău 92 javascript mongodb node.js
我使用NodeJS在MongoDB中插入文档.使用collection.insert
我可以将文档插入数据库,如下代码所示:
// ...
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId; // = ???
});
// ...
Run Code Online (Sandbox Code Playgroud)
如何获取_id
插入的对象?
有没有办法让_id
没有插入最新的对象_id
?
假设很多人在同一时间访问数据库,我不能确定最新的id是插入对象的id.
geo*_*yer 84
回调的第二个参数collection.insert
将返回插入的doc或docs,它应该有_ids.
尝试:
collection.insert(objectToInsert, function(err,docsInserted){
console.log(docsInserted);
});
Run Code Online (Sandbox Code Playgroud)
并检查控制台,看看我的意思.
Ion*_*zău 82
比使用第二个参数更短的方法collection.insert
是使用objectToInsert._id
返回_id
(回调函数内部,假设它是一个成功的操作).
NodeJS的Mongo驱动程序将该_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
});
Run Code Online (Sandbox Code Playgroud)
Ser*_*ice 16
正如ktretyak所说,获取插入文档的ID最好的方法是在结果对象上使用insertedId属性.在我的情况下result._id没有工作,所以我不得不使用以下:
db.collection("collection-name")
.insertOne(document)
.then(result => {
console.log(result.insertedId);
})
.catch(err => {
// handle error
});
Run Code Online (Sandbox Code Playgroud)
如果你使用回调也是一样的.
Sid*_*dak 11
我实际上为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
}
});
Run Code Online (Sandbox Code Playgroud)
您可以使用异步函数自动获取 _id 字段,而无需操作数据对象:
\nasync function save() {\n const data = {\n name: "John"\n }\n\n await db.collection('users').insertOne(data)\n\n return data\n}\n
Run Code Online (Sandbox Code Playgroud)\n返回(data
对象):
\n\n{
\n
\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0_id: '5dbff150b407cc129ab571ca',
\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0name: '约翰',
\n}
Mongo将完整的文档作为回调对象发送,因此您只需从那里获取它.
例如
collection.save(function(err,room){
var newRoomId = room._id;
});
Run Code Online (Sandbox Code Playgroud)
如果您想使用“_id”,请使用 simpley
result.insertedId.toString()
Run Code Online (Sandbox Code Playgroud)
// toString 将从十六进制转换
归档时间: |
|
查看次数: |
90404 次 |
最近记录: |