node.js Node + Mongoose:获取最后插入的ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6074245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node + Mongoose: Get last inserted ID?
提问by trnc
I want to retrieve the last inserted _id, using mongoose as MongoDB wrapper for node.js. I've found the following tutorial, but I can't change any node modules because the app runs on a public server:
我想检索最后插入的_id,使用 mongoose 作为 node.js 的 MongoDB 包装器。我找到了以下教程,但我无法更改任何节点模块,因为该应用程序在公共服务器上运行:
Getting "Last Inserted ID" (hint - you have to hack Mongoose)
获取“最后插入的 ID”(提示 - 你必须破解 Mongoose)
Any other ideas? This what I want to do:
还有其他想法吗?这是我想要做的:
- Insert new user
- Get user's
_idvalue - Set a new session based on user's id
- Redirect to /
- 插入新用户
- 获取用户
_id价值 - 根据用户 ID 设置新会话
- 重定向到 /
Thanks!
谢谢!
回答by Peter Lyons
I'm using mongoose version 1.2.0 and as soon as I created a new instance of a mongoose model, the _idis already set.
我使用的是 mongoose 1.2.0 版,一旦我创建了 mongoose 模型的新实例,_id就已经设置好了。
coffee> u = new User()
[object Object]
coffee> u._id
4dd68fc449aaedd177000001
I also verified that after I call u.save()the _idremains the same. I verified via MongoHub that this is indeed the real ID saved into MongoDB.
我也验证了我称之为后u.save()的_id保持不变。我通过 MongoHub 验证,这确实是保存在 MongoDB 中的真实 ID。
回答by Kari-S
If you explicitly declare
如果你明确声明
_id: Schema.ObjectId
for your model, then the ObjectId will not be available after new or save. This is probably a bug.
对于您的模型,则在新建或保存后 ObjectId 将不可用。这可能是一个错误。
回答by JayCrossler
If you're looking to get the last inserted _id of a sub object, then create the object, and add it to the item. Here's an example in NowJS using MongoDB and Mongoose (to add some schema sugar) which then converts the result to JSON to send back to the client:
如果您希望获得子对象的最后插入的 _id ,则创建该对象,并将其添加到项目中。这是 NowJS 中使用 MongoDB 和 Mongoose(添加一些模式糖)的示例,然后将结果转换为 JSON 以发送回客户端:
var nowRoomID = this.now.room;
var Conversation = mongoose.model('Conversation');
Conversation.findById(convID, function(error, conversation) {
var Blip = mongoose.model('Blip');
var createdBlip = new Blip();
createdBlip.author= nowUserName;
createdBlip.authorid = parsed.authorid;
createdBlip.body = revisedText;
createdBlip.created_at = new Date();
createdBlip.modified_at = new Date();
conversation.blips.push(createdBlip);
parsed._id = createdBlip._id; //NOTE: ID ACCESSED HERE
message = JSON.stringify(parsed);
conversation.save(function (err) {
if (!err) {
console.log('Success - saved a blip onto a conversation!');
nowjs.getGroup(nowRoomID).now.receiveMessage(nowUserName, message);
}
});
回答by grantwparks
I just get the id from the document passed to the callback, since save returns the saved document.
我只是从传递给回调的文档中获取 id,因为 save 返回保存的文档。
回答by Chris Fulstow
With MongoDB, if you don't explicitly set a document's _idvalue then the client driver will automatically set it to an ObjectIdvalue. This is different from databases that might generate IDs on the server and need another query to retrieve it, like with SQL Server's scope_identity()or MySQL's last_insert_id().
使用 MongoDB,如果您没有明确设置文档的_id值,那么客户端驱动程序将自动将其设置为ObjectId值。这与可能在服务器上生成 ID 并需要另一个查询来检索它的数据库不同,例如 SQL Server 的scope_identity()或 MySQL 的last_insert_id()。
This allows you to insert data asynchronously because don't need to wait for the server to return an _idvalue before you continue.
这允许您异步插入数据,因为_id在继续之前不需要等待服务器返回值。
So, as shown is Peter's answer, the _idis available before the document is saved to the database.
因此,如 Peter 的回答所示,_id在将文档保存到数据库之前是可用的。
回答by Dineshaws
Check below url
检查以下网址
http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html
http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html
you will find following code in given url
您会在给定的 url 中找到以下代码
var document = {name:"David", title:"About MongoDB"};
collection.insert(document, {w: 1}, function(err, records){
console.log("Record added as "+records[0]._id);
});

