How to relate two models with mongoose?

1

I have two models in my bd

user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');

// User Model
var UserSchema = new Schema({
  name: {
        type: String,
        unique: true,
        required: true
    },
  password: {
        type: String,
        required: true
    }
});

UserSchema.add({
  email: 'string',
  about: 'string',
  age: 'number',
  active: 'Boolean',
  phone: 'number'
  });

and actions.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');

var ActionSchema = new Schema({
  postPerm: 'Boolean',
  sendEmailPerm: 'Boolean',
  editPerm: 'Boolean'
});

How do I link to them?

In case I want USER to have a ACTIONS related where I will control them

    
asked by anonymous 29.01.2018 / 19:14

1 answer

1

The closest that MongoDB can have to a relational database is the use of Reference , where you can create a reference between documents.

  

In case I want every USER to have a related ACTIONS

MongoDB is a NoSQL and does not have something like constraint of mandatory field between primary and foreign key at the bank level, however mongoose has middleware validation that helps in some tasks like this (in your specific case, not to save an action without user, or vice versa).

Reference example

[...]
var UserSchema = new Schema({
  name: {
        type: String,
        unique: true,
        required: true
    },
  password: {
        type: String,
        required: true
    },
  actions: [{ type: Schema.Types.ObjectId, ref: 'Action' }] // aqui é feita a referencia entre os documentos
});

var ActionSchema = new Schema({
  postPerm: 'Boolean',
  sendEmailPerm: 'Boolean',
  editPerm: 'Boolean'
});

var User = mongoose.model('User', UserSchema);
var Action = mongoose.model('Action', ActionSchema);
    
29.01.2018 / 20:06