How to set ObjectId as a data type in mongoose

前端 未结 4 1733
感动是毒
感动是毒 2020-12-07 11:31

Using node.js, mongodb on mongoHQ and mongoose. I\'m setting a schema for Categories. I would like to use the document ObjectId as my categoryId.

var mongoos         


        
4条回答
  •  悲&欢浪女
    2020-12-07 11:43

    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:

    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:

    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

提交回复
热议问题