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

259
Vistas
adding data to schema optionally in mongodb using node js

I made a 2 mongodb schema in which one is depend on another schema and my both look like this

ownerSchema.js

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

shopSchema.js

var shopSchema = Schema({
    _id       : String,
    shopName  : String,
    location  : String,
    startDate : Date,
    endDate   : Date
});
var Shop  = mongoose.model('Shop', shopSchema);

and this is my add function

const addOwner = async (req, res) => {
 
    const { shopName, shopLocation } = req.body.shopPlace;
    const shop = new Shop({
      shopName,
      shopLocation,
    });
    await shop.save();

    const { ownerId, fname, lname } = req.body;
    const newOwner = new Owner({
      ownerId,
      fname,
      lname,
      shopPlace: shop._id,
    });
    await newOwner.save();
};

Problem is sometimes i dont want shopPlace data it should be blank

but I am sending only ownerId, fname, lname from postman it does not saving in my database is there any possible way that if I dont want shopPlace still it should save data to my schema it should be optional

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

0

In your model you can set a default value for shopPlace as follows:

shopPlace : { 
   type: Schema.Types.ObjectId,
   ref: 'Shop',
   default: null
}

So, if you don't provide shopPlace when you create a new Owner, it will be null

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