How to relate two "models" to Mongoosis?

Asked

Viewed 1,339 times

2

I have two models in my comic book

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 connect them?

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

  • Link with good relationship answers: https://stackoverflow.com/questions/35245685/mongoose-one-to-many/35245953

1 answer

1


The closest Mongodb can come to relational banking is the use of Reference, where it is possible to create reference between documents.

In case I want every USER to have a related ACTIONS

Mongodb is a Nosql and has nothing like Constraint mandatory field between primary and foreign key at 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).

Example of the Ference

[...]
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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.