MongoDB自定义_id字段问题:自定义值被自动覆盖,Node.js Schema未声明_id是否需配置?
_id in Mongoose Without Auto-Generated ObjectId Great question—let’s break down why this is happening and how to fix it clearly:
The root issue here is Mongoose’s default behavior for the _id field. Even if you don’t explicitly declare _id in your Schema, Mongoose automatically adds an implicit _id field of type ObjectId behind the scenes, with the auto option set to true. This means it will always generate a random ObjectId for new documents, overriding any custom value you send in your request.
To use a custom _id value, you do need to explicitly declare the _id field in your Schema, and configure it to accept your desired data type instead of relying on the auto-generated ObjectId. Here’s a practical example:
const mongoose = require('mongoose'); // Define your schema with explicit _id configuration const yourCollectionSchema = new mongoose.Schema({ _id: { type: String, // You can also use Number, ObjectId (for custom ObjectIds), etc. required: true // Ensures a custom value is provided on document creation }, // Add your other document fields below name: String, createdAt: Date }); const YourCollectionModel = mongoose.model('YourCollection', yourCollectionSchema);
With this setup, when you send a request with a custom _id (e.g., {"_id": "user_12345", "name": "Test User"}), Mongoose will respect your custom value instead of generating a new ObjectId.
Key Reminders:
- Ensure your custom
_idvalues are unique across the collection—MongoDB enforces uniqueness on the_idfield, so duplicates will trigger a duplicate key error. - You can use any valid BSON type for
_id(String, Number, ObjectId, etc.)—just make sure the type in your Schema matches what you’re sending in requests.
内容的提问来源于stack exchange,提问作者BranOIE

