Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement: Cast ObjectId to string inside of MongooseMap. #9936

Closed
jhunterkohler opened this issue Feb 15, 2021 · 1 comment
Closed

Enhancement: Cast ObjectId to string inside of MongooseMap. #9936

jhunterkohler opened this issue Feb 15, 2021 · 1 comment

Comments

@jhunterkohler
Copy link
Contributor

jhunterkohler commented Feb 15, 2021

Enchancment

I am working on a project that uses the MongooseMap type and thought one simple line would help within the get, set, and delete instance methods. We just add a short conversion onto the following functions:

get(key, options) {
options = options || {};

set(key, value) {
checkValidKey(key);

mongoose/lib/types/map.js

Lines 109 to 110 in aef25e0

delete(key) {
this.set(key, undefined);

Namely, insert:

if(key instanceof ObjectId) {
    key = key.toString();
}

Also require ObjectId in the header.

const Mixed = require('../schema/mixed');
const deepEqual = require('../utils').deepEqual;

const ObjectId = require('./objectid')

Example

This implicit cast would be more or less expected as ObjectId is so frequently represented as a string. This example just shows a case where data would be stored in conjunction with a list of references. We want to get the data upon user requests, and calling the user id on the Map's hash-table will obviously be faster than a linear scan (or at least less painfull to look at then a toString call every 10 seconds).

const UserSchema = {
    name: String
}

const User = mongoose.model('User', UserSchema);

const GroupSchema = {
    members: {
        type: Map,
        of: { 
            read_receipts: Bool,
            share_location: Bool,
            follow_globals: Bool,
            nickname: String,
            role: {
                type: String
                enum: ['member', 'creator', 'admin']
            },
         }
     }
}

GroupSchema.methods.add
    = function add(userId, role = 'member') {
        this.members.set(userId, { role });
    };

GroupSchema.methods.remove
    = function remove(userId) {
        this.members.delete(userId);
     };

const Group = model('Group', GroupSchema);

TL;DR

Add ObjectId conversion to map so we don't have to think about converting to string. Maintain object relationships with ObjectIds meant to represent other docs.

@vkarpov15
Copy link
Collaborator

Fixed by #9938

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants