Database model with Mongoose

0

I would like to know if it is possible to implement a document that has as an attribute an array of documents and how to do it. For example:

Usuario = {
  nombre: String,
  archivo: [{
    ruta: String
  }]
}
    
asked by SaitoHs 23.02.2017 в 19:15
source

2 answers

1

There are two ways in which a document can have an array of documents:

  • Subdocuments
  • Reference documents
  • Subdocuments

    A document can have subdocuments like any other field. Based on your example:

    const UserSchema = new Schema({
      nombre: {
        type: String,
        required: true
      },
      archivos: [{
        ruta: {
          type: String,
          required: true
        }
      }]
    });
    

    In the previous example, a document can have many documents in archivos . To consult it is very simple:

    User
      .findById(id)
      .then(user => {
         console.log(user.archivos); // [ { ruta: '/tmp/amvf3vc.pdf' } ]
      });
    

    Reference documents

    Reference documents are only _id s that refer to other documents that may even be in another collection. This is very similar to the classic relationships in SQL.

    const UserSchema = new Schema({
      nombre: {
        type: String,
        required: true
      },
      archivos: [{
        ruta: {
          type: ObjectId,
          ref: 'Archivo',
          required: true
        }
      }]
    });
    

    In this particular case, Archivo is another collection:

    const ArchivoSchema = new Schema({
      name: {
        type: String,
        required: true
      },
      weight: {
        type: Number,
        required: true
      },
      createAt: {
        type: Date,
        required: true,
        default: Date.Now
      }
    });
    

    When you create a User document and add Archivos , the archivos field will have the identifiers of the Archivo documents associated with that user:

    archivos: [
      '',
      '',
      ''
    ]
    

    To consult is a little different. If we consult as in the previous example, you would obtain the document with the field files as such, but without the documents to which they refer. In this case, we need to populate the main document with the subdocuments to which it refers.

    User
      .findById(id)
      .then(user => {
         let _user = user;
         delete _user.archivos;
    
         user.archivos.forEach(arch => {
           Archivo.findById(arch).then(doc => {
             _user.push(doc);
           });
         });
    
         resolve(_user);
      });
    

    Fortunately, ODMs like Mongoose in Node.js do that for you:

    User.findById(id).populate('archivos');
    
      

    When to use subdocuments vs. references?

    If it makes sense to put a separate collection, then you should use references. For example, if you have a collection that can be used for other things apart from your relationship with another, use references. On the other hand, if your separate collection only serves a small and unique purpose that depends on another collection, use it as a subdocument.

        
    answered by 23.03.2017 в 04:14
    0

    Of course it is possible. I recommend using the Mongoose package, which makes it easier to create NoSQL schemas as well as to handle such models with very useful methods.

    More information here. link

    An example:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    
    var userSchema = mongoose.Schema({
    
        email: {type: String},
        password: {type: String},
        firstname: {type: String},
        lastname: {type: String},
    
    
    }, {
      timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
      }
    });
    
    module.exports = mongoose.model('User', userSchema);
    
        
    answered by 10.03.2017 в 02:26