Mongoose most adequate way to automate the reference of newly created document on documents of different collection

Viewed 19

In a MEAN stack learning context I need a MongoDb database that among other stuff will store User, Resource and Resource Use following the schemes:

Schema User

import { Schema } from 'mongoose';

const schema_user = new Schema({
    name: {
        type: String, 
        required:  [true, '...'] 
    }, 

    // ...

    resource_use: [{ type: Schema.Types.ObjectId, ref: 'Resource_Use'}]

});

Schema Resource

import { Schema } from 'mongoose';

const schema_resouce = new Schema({

  nr: {
      type: String,
      required: [true, '...'],
      unique: [true, '...']
  },

  // ...

  resource_use: [{ type: Schema.Types.ObjectId, ref: 'Resource_Use' }]

});

Schema Resource Use

import { Schema } from 'mongoose';

const schema_resource_use = new Schema({
    idu: {
        type: Schema.Types.ObjectId,
        required: [true, '...'], ref: 'User'
    },
    idr: {
        type: Schema.Types.ObjectId,
        required: [true, '...'], ref: 'Resource'
    },
    // ...
});

So, when I create a new resource_use document, I have to reference user doc and a resource doc for the new document, and after the document is created I need to insert into the referenced documents the reference of the created document.

Basically I am struggling to find out which would be more suitable as to automate the task: hooks, instance methods, model queries, ...

I guess streams would be out of the question, since I can't make to have a replicaset configuration.

Moreover, I need to favor organization separating the necessary function implementation from the schema file.

Any help is thanked.

1 Answers

I can achieve the desired through "middleware" the following manner:

resource_use.post('/', async (req, res, next) => {

    const rsrcuse = req.body

    let rsrc_use = await req.context.models.Resource_Use.create(rsrcuse)
        .catch(error => next(error));
    
    // relying here on the created id
    await req.context.models.User.findByIdAndUpdate(
        rsrcuse.idu,
        { "$push": { "resource_use": rsrc_use.id } })
        .catch(error => next(error));

    await req.context.models.Resource.findByIdAndUpdate(
        rsrcuse.idr,
        { "$push": { "rsrc_use": rsrc_use.id } })
        .catch(error => next(error));

    rsrc_use = await rsrc_use.populate(['idu', 'idr']);

    res
        .status(201)
        .json(rsrc_use)

    res.send;
});

Nevertheless, amidst all my doubts, I wonder if and how this could be more automated specially regarding the number of calls to the database.

Related