乐闻世界logo
搜索文章和话题

How do i get the objectid after i save an object in mongoose

5 个月前提问
3 个月前修改
浏览次数49

6个答案

1
2
3
4
5
6

在 Mongoose 中,每个保存到 MongoDB 的文档都会自动获得一个 _id 属性,它是一个 ObjectId 类型的默认属性。当您使用 Mongoose 的模型创建并保存一个新的文档时,Mongoose 在内部会调用 MongoDB 的 insert 操作,该操作会生成一个新的 ObjectId。这个 _id 是唯一的,并且会被自动添加到您的文档中。

保存文档后获取文档的 _id(即 ObjectId)非常直接。在您调用 .save() 方法并通过回调或者 Promise 获取到保存操作的结果时,您可以直接访问文档的 _id 属性。

以下是一个使用 Promise 的例子:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // 定义一个简单的模式 const mySchema = new Schema({ name: String }); // 创建模型 const MyModel = mongoose.model('MyModel', mySchema); // 创建一个文档实例 const myDocument = new MyModel({ name: 'John Doe' }); // 保存文档 myDocument.save().then((savedDocument) => { // 文档保存后,我们可以直接获取 _id console.log('Document saved with _id:', savedDocument._id); }).catch((error) => { console.error('Error saving document:', error); });

在上述例子中,当 .save() 方法成功执行后,它将返回一个包含已保存文档的 Promise 对象。在这个 Promise 的.then 部分,我们可以通过 savedDocument._id 来访问这个新创建的 ObjectId。如果保存操作失败,则会进入 .catch 部分,我们可以处理错误信息。

如果您是在使用 async/await 语法,那么代码会是这样的:

javascript
// 使用 async/await 保存文档 async function saveDocument() { try { const savedDocument = await myDocument.save(); console.log('Document saved with _id:', savedDocument._id); } catch (error) { console.error('Error saving document:', error); } } // 执行保存操作 saveDocument();

在这个 async/await 的例子中,我们在一个异步函数 saveDocument 中使用了 await 关键字来等待 myDocument.save() 的执行结果。如果执行成功,我们可以直接通过 savedDocument._id 访问到 _id 属性。如果执行时遇到错误,则会进入 catch 块,在这里我们可以处理错误。

2024年6月29日 12:07 回复

This just worked for me:

shell
var mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/lol', function(err) { if (err) { console.log(err) } }); var ChatSchema = new Schema({ name: String }); mongoose.model('Chat', ChatSchema); var Chat = mongoose.model('Chat'); var n = new Chat(); n.name = "chat room"; n.save(function(err,room) { console.log(room.id); }); $ node test.js 4e3444818cde747f02000001 $

I'm on mongoose 1.7.2 and this works just fine, just ran it again to be sure.

2024年6月29日 12:07 回复

Mongo sends the complete document as a callbackobject so you can simply get it from there only.

for example

shell
n.save(function(err,room){ var newRoomId = room._id; });
2024年6月29日 12:07 回复

You can manually generate the _id then you don't have to worry about pulling it back out later.

shell
var mongoose = require('mongoose'); var myId = mongoose.Types.ObjectId(); // then set it manually when you create your object _id: myId // then use the variable wherever
2024年6月29日 12:07 回复

You can get the object id in Mongoose right after creating a new object instance without having to save it to the database.

I'm using this code work in mongoose 4. You can try it in other versions.

shell
var n = new Chat(); var _id = n._id;

or

shell
n.save((function (_id) { return function () { console.log(_id); // your save callback code in here }; })(n._id));
2024年6月29日 12:07 回复

Other answers have mentioned adding a callback, I prefer to use .then()

shell
n.name = "chat room"; n.save() .then(chatRoom => console.log(chatRoom._id));

example from the docs:.

shell
var gnr = new Band({ name: "Guns N' Roses", members: ['Axl', 'Slash'] }); var promise = gnr.save(); assert.ok(promise instanceof Promise); promise.then(function (doc) { assert.equal(doc.name, "Guns N' Roses"); });
2024年6月29日 12:07 回复

你的答案