在 Mongoose 中,每个保存到 MongoDB 的文档都会自动获得一个 _id
属性,它是一个 ObjectId 类型的默认属性。当您使用 Mongoose 的模型创建并保存一个新的文档时,Mongoose 在内部会调用 MongoDB 的 insert
操作,该操作会生成一个新的 ObjectId。这个 _id
是唯一的,并且会被自动添加到您的文档中。
保存文档后获取文档的 _id
(即 ObjectId)非常直接。在您调用 .save()
方法并通过回调或者 Promise 获取到保存操作的结果时,您可以直接访问文档的 _id
属性。
以下是一个使用 Promise 的例子:
javascriptconst 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
块,在这里我们可以处理错误。