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

How to set a schema-field to be the ID using Mongoose?

1个答案

1

In Mongoose, setting a schema field as an ID type typically means defining it as a MongoDB ObjectId type. ObjectId is a special data type in MongoDB, commonly used to represent a unique document identifier (_id).

To define a field as an ObjectId type in Mongoose, use Schema.Types.ObjectId. This is typically used for fields that reference other documents. For example, if you have a user model and a post model, and you want to reference the user who created the post in the post model, you can set the user field in the post model as follows:

javascript
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const postSchema = new Schema({ // ...other fields author: { type: Schema.Types.ObjectId, ref: 'User' // Here, it specifies that this ObjectId references the User model } // ...other fields }); const Post = mongoose.model('Post', postSchema);

In the above example, the author field is set as an ObjectId type, and the ref property specifies that this ID references an instance of the User model.

If you want to set a field as the primary key (i.e., the default _id field of a document), you can directly use the ObjectId type when defining the schema. This is typically handled automatically, and you don't need to explicitly specify it because every Mongoose model defaults to having an _id field of type ObjectId.

If you want to explicitly set the _id field, you can do the following:

javascript
const userSchema = new Schema({ _id: Schema.Types.ObjectId, // Explicitly define _id field as ObjectId type // ...other fields }); const User = mongoose.model('User', userSchema);

However, it is generally not recommended to manually set the _id field unless you have specific requirements, as MongoDB automatically generates a unique ObjectId for each newly created document.

2024年6月29日 12:07 回复

你的答案