节点 + Mongoose:获取最后插入的ID?

发布于 2024-11-09 10:02:50 字数 388 浏览 0 评论 0 原文

我想检索最后插入的 _id,使用 mongoose 作为 node.js 的 MongoDB 包装器。我找到了以下教程,但无法更改任何节点模块,因为该应用程序在公共服务器上运行:

获取“最后插入的 ID”(提示 - 你必须破解 Mongoose)

还有其他想法吗?这就是我想要做的:

  • 插入新用户
  • 获取用户的_id
  • 根据用户的id设置新会话
  • 重定向到/

谢谢!

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:

Getting "Last Inserted ID" (hint - you have to hack Mongoose)

Any other ideas? This what I want to do:

  • Insert new user
  • Get user's _id value
  • Set a new session based on user's id
  • Redirect to /

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

颜漓半夏 2024-11-16 10:02:50

我使用的是 mongoose 版本 1.2.0,一旦创建了 mongoose 模型的新实例,_id 就已设置。

coffee> u = new User()
[object Object]
coffee> u._id
4dd68fc449aaedd177000001

我还验证了在调用 u.save() 后,_id 保持不变。我通过 MongoHub 验证这确实是保存到 MongoDB 中的真实 ID。

I'm using mongoose version 1.2.0 and as soon as I created a new instance of a mongoose model, the _id is already set.

coffee> u = new User()
[object Object]
coffee> u._id
4dd68fc449aaedd177000001

I also verified that after I call u.save() the _id remains the same. I verified via MongoHub that this is indeed the real ID saved into MongoDB.

孤独难免 2024-11-16 10:02:50

如果您为模型显式声明

    _id: Schema.ObjectId

,则 ObjectId 在新建或保存后将不可用。
这可能是一个错误。

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.

夜司空 2024-11-16 10:02:50

如果您希望获取子对象最后插入的_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);
                        }

                    });

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:

                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);
                        }

                    });
迷乱花海 2024-11-16 10:02:50

使用 MongoDB,如果您没有显式设置文档的 _id 值,则客户端驱动程序会自动将其设置为 ObjectId 值。这与可能在服务器上生成 ID 并需要另一个查询来检索它的数据库不同,例如 SQL Server 的 scope_identity() 或 MySQL 的 last_insert_id()

这允许您异步插入数据,因为无需等待服务器返回 _id 值即可继续。

因此,正如 Peter 的回答所示,_id 在文档保存到数据库之前就可用。

With MongoDB, if you don't explicitly set a document's _id value then the client driver will automatically set it to an ObjectId value. 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().

This allows you to insert data asynchronously because don't need to wait for the server to return an _id value before you continue.

So, as shown is Peter's answer, the _id is available before the document is saved to the database.

╭⌒浅淡时光〆 2024-11-16 10:02:50

我只是从传递给回调的文档中获取 id,因为 save 返回已保存的文档。

I just get the id from the document passed to the callback, since save returns the saved document.

梦醒灬来后我 2024-11-16 10:02:50

检查以下网址

http://mongodb.github.io/node- mongodb-native/markdown-docs/insert.html

你会在给定的url中找到以下代码

    var document = {name:"David", title:"About MongoDB"};
   collection.insert(document, {w: 1}, function(err, records){
  console.log("Record added as "+records[0]._id);
});

Check below url

http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

you will find following code in given url

    var document = {name:"David", title:"About MongoDB"};
   collection.insert(document, {w: 1}, function(err, records){
  console.log("Record added as "+records[0]._id);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文