Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
How to add refrence and data in another scheme in mongoose

I'm building a Mongoose schema for a store

I have two schema owner and shop I am trying to add data in show with ref as owner but dont know how to do it

here is my schema structure

const mongoose = require("mongoose");

var shopSchema = Schema({
    location  : String,
    startDate : Date,
    endDate   : Date
});

var ownerSchema = Schema({
    fname     : String,
    lname     : String,
    shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }]
});


var Shop  = mongoose.model('Shop', shopSchema);
var Owner = mongoose.model('Owner', ownerSchema);

so this is how my schema look like and I am trying to add detail of owner and shop but don't know how to do it if it is single schema I can easily do it but with ref I can't

const Owner = require("../models/ownerSchema");

const addTask = async (req, res) => {
    let newOwmer = new Owner(req.body);
    try {
    newOwner = await newOwner.save();
    cosnole.log("Added Successfully");
  } catch (err) {
    console.log(err);
  }
};

I can add easily but dont know how to add shop

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You would have to do something like this

const mongoose = require("mongoose");

var ownerSchema = Schema({
  fname     : String,
  lname     : String,
  shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }]
});
var Owner = mongoose.model('Owner', ownerSchema);

var shopSchema = Schema({
    location  : String,
    startDate : Date,
    endDate   : Date,
    owner: Owner
});

var Shop  = mongoose.model('Shop', shopSchema);

Then when you create a shop, create an owner first, and add the owner at the creation of a shop. Maybe like this

// Import your shop and owner models
const fetchedOwner = await Owner.get('the-owner-id')
const createShop = {
  location  : 'London'
  startDate : 'some date'
  endDate   : 'another date'
  owner: fetchedOwner
}
await Shop.create(createShop)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda