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

How to set objectid as a data type in mongoose

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

6个答案

1
2
3
4
5
6

在 Mongoose 中,如果您想要将模型中的某个字段设置为 ObjectId 数据类型,通常是为了创建一个引用其他MongoDB文档的字段。您可以使用 Schema.Types.ObjectId 来指定字段类型。这通常与 ref 选项结合使用,以指明该 ObjectId 引用的模型。

以下是一个如何在Mongoose模型中定义 ObjectId 字段的例子:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // 定义一个新的Schema const userSchema = new Schema({ // ... 其他字段 // 这里定义了一个名为`profile`的字段,它引用了`Profile`模型 profile: { type: Schema.Types.ObjectId, ref: 'Profile' } }); // 创建一个名为`User`的模型 const User = mongoose.model('User', userSchema);

在上述例子中,profile 字段被设置为 ObjectId 类型,并且通过 ref 属性与 Profile 模型相关联。这意味着 profile 字段应该包含一个存储在 Profile 集合中的文档的ID。

当您在使用Mongoose查询包含 ObjectId 引用的文档时,可以使用 .populate() 方法来自动替换这些字段的 ObjectId 为关联文档的数据。例如:

javascript
User.findById(userId) .populate('profile') // 这会获取 `profile` 字段引用的 `Profile` 文档 .exec((err, user) => { if (err) { // 处理错误 } else { // 这里的 `user.profile` 将是一个完整的 `Profile` 文档而不只是一个ID console.log(user.profile); } });

这个 .populate() 调用告诉Mongoose,在查询完成时填充 profile 字段,而不仅仅是返回 ObjectId。这样,您就可以访问关联的 Profile 文档的所有信息。

2024年6月29日 12:07 回复

Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.

For this reason, it doesn't make sense to create a separate uuid field.

In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.

Here is an example:

shell
var mongoose = require('mongoose'); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var Schema_Product = new Schema({ categoryId : ObjectId, // a product references a category _id with type ObjectId title : String, price : Number });

As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.

However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.

Check it out:

shell
var mongoose = require('mongoose'); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var Schema_Category = new Schema({ title : String, sortIndex : String }); Schema_Category.virtual('categoryId').get(function() { return this._id; });

So now, whenever you call category.categoryId, mongoose just returns the _id instead.

You can also create a "set" method so that you can set virtual properties, check out this link for more info

2024年6月29日 12:07 回复

I was looking for a different answer for the question title, so maybe other people will be too.

To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

shell
const Book = mongoose.model('Book', { author: { type: mongoose.Schema.Types.ObjectId, // here you set the author ID // from the Author colection, // so you can reference it required: true }, title: { type: String, required: true } });
2024年6月29日 12:07 回复

My solution on using ObjectId

shell
// usermodel.js const mongoose = require('mongoose') const Schema = mongoose.Schema const ObjectId = Schema.Types.ObjectId let UserSchema = new Schema({ username: { type: String }, events: [{ type: ObjectId, ref: 'Event' // Reference to some EventSchema }] }) UserSchema.set('autoIndex', true) module.exports = mongoose.model('User', UserSchema)

Using mongoose's populate method

shell
// controller.js const mongoose = require('mongoose') const User = require('./usermodel.js') let query = User.findOne({ name: "Person" }) query.exec((err, user) => { if (err) { console.log(err) } user.events = events // user.events is now an array of events })
2024年6月29日 12:07 回复

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

shell
let UserSchema = new Schema({ username: { type: String }, events: [{ type: ObjectId, ref: 'Event' // Reference to some EventSchema }] })

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:

shell
let UserSchema = new Schema({ username: { type: String }, events: { type: ObjectId, ref: 'Event' // Reference to some EventSchema } })

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

2024年6月29日 12:07 回复

You can directly define the ObjectId

var Schema = new mongoose.Schema({ categoryId : mongoose.Schema.Types.ObjectId, title : String, sortIndex : String })

Note: You need to import the mongoose module

2024年6月29日 12:07 回复

你的答案