Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda