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

388
Vistas
How to deconstruct protected routes/users and posts in the same .create() method in mongoose/js?

I'm wondering how to use the .create() method with a protected route while using deconstructed JavaScript. Without the protected route, I can deconstruct my schema and use req.body in .create(...) like below.

const { title, year, producer, director, licenseStart, licenseEnd, platform, requestorName, requestorEmail, requestorDepartment, price, notes } = req.body

Without deconstructing it, I can make it work in .create() and .save() but it is 14-15 lines and does not feel like best practice. See below.

const newPurchase = new Purchase({
    user: req.user.id,
    title: req.body.title,
    year: req.body.year,
    producer: req.body.producer,
    director: req.body.director,
    licenseStart: req.body.licenseStart,
    licenseEnd: req.body.licenseEnd,
    platform: req.body.platform,
    requestorName: req.body.requestorName,
    requestorEmail: req.body.requestorEmail,
    requestorDepartment: req.body.requestorDepartment,
    price: req.body.price,
    notes: req.body.notes
});

const savedPurchase = await newPurchase.save();

My problem is...how the heck do you deconstruct both user:req.user.id and the req.body properties and use them both in the same .create() method? .create(req.body) works, but .create(req.body, { user: req.user.id }) does not. I've tried several other variations as well.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Hi I'm not really sure what you mean by making this work:

.create(req.body, { user: req.user.id })

But I usually use the .create() like this:

async function createUser(req, res) {
  const {
    firstName,
    lastName,
    gender,
    profilePicture,
    email,
    password
  } =
  req.body;

  try {
    const schema = object().keys({
      firstName: string().required(),
      lastName: string().required(),
      gender: string().optional(),
      profilePicture: string().optional(),
      email: string().required(),
      password: string().required(),
    });

    const validation = validate(req.body, schema);
    if (validation.error !== null)
      throw new Error(validation.error.details[0].message);

    const user = await User.findOne({
      email
    });
    if (user) {
      res.status(400).json({
        success: false,
        message: "Email Already Exist"
      });
      return;
    }
    const data = await User.create({
      firstName,
      lastName,
      gender,
      profilePicture,
      email,
      password,
      lastLogin: new Date(),
    });
    const newUser = await User.findById(data._id);

    res.json({
      success: true,
      message: "user details",
      data: newUser,
    });
  } catch (error) {
    console.error(error);
    res.json({
      success: false,
      message: "user not found",
      error
    });
  }
}

Hopes this helps

over 4 years ago · Santiago Trujillo Denunciar

0

I figured out the answer to my own question. I thought I had tried this before but it worked this time.

const setPurchases = asyncHandler(async (req, res) => {

const {title, year, producer, director, licenseStart, licenseEnd, platform, requestorName, requestorEmail, requestorDepartment, price, notes} = req.body
        
if (!title || !year || !producer || !director || !licenseStart || !licenseEnd|| !platform || !requestorName || !requestorEmail || !requestorDepartment || !price || !notes){
    res.status(400)
    throw new Error('Please fill in all the fields')
}

**const purchase = await Purchase.create(Object.assign({user:req.user.id}, req.body));**

This allowed me to deconstruct the Purchase Schema object and use both it and the user object in the create() method. This is a lot cleaner than the code below and having user: req.user.id plus 12 req.body objects like title: req.body.title, name: req.body.name, year: year.req.body.year, producer... etc in the .create() method. The code above is much cleaner than below and what I've been looking for. Hopefully it will help anyone else dealing with the same issue or a novice like me. Also keep in mind it works with .save() as well, albeit a bit different as shown in my original question.

const setPurchases = asyncHandler(async (req, res) => {
        
if (!title || !year || !producer || !director || !licenseStart || !licenseEnd|| !platform || !requestorName || !requestorEmail || !requestorDepartment || !price || !notes){
    res.status(400)
    throw new Error('Please fill in all the fields')
}

const purchase = await Purchase.create({
    title: req.body.title,
    year: req.body.year,
    producer: req.body.producer,
    director: req.body.director,
    licenseStart: req.body.licenseStart,
    licenseEnd: req.body.licenseEnd,
    platform: req.body.platform,
    requestorName: req.body.requestorName,
    requestorEmail: req.body.requestorEmail,
    requestorDepartment: req.body.requestorDepartment,
    price: req.body.price,
    notes: req.body.notes})
over 4 years ago · Santiago Trujillo 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