Search code examples
javascriptnode.jsmongodbmongoose

Why isn't the product being added to the user's 'products' using mongodb $push although the post is successful


I am trying to add a product but also add the product into a customers account by adding it to the 'products' array in the database.

I am using the customers email as the frontend will only need an admin to put the customers email to find their account.

Below is the request

export const addProduct = async (req, res, next)=> {
  try {
    const newProduct = new Product({
    userEmail: req.body.email,
    ...req.body,
  });
    const savedProduct = await newProduct.save();
    await User.findOneAndUpdate({email: req.body.email}, { $push: { products: newProduct }})
    res.status(201).json(savedProduct);
  } catch (err) {
    console.log(err)
    next(err);
  }
}

Here is the schema:

import mongoose from 'mongoose';
const {Schema} = mongoose

const UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true,
    },
    password: {
        type: String,
        required: true,
        min: 6,
    },
    fName: {
        type: String,
        required: false,
    },
    lName: {
        type: String,
        required: false,
    },
    address: {
        type: String,
        required: false,
    },
    postcode: {
        type: String,
        required: false,
    },
    phone: {
        type: String,
        required: false,
    },
    accountNumber: {
        type: String,
        required: false,
    },
    sortCode: {
        type: String,
        required: false,
    },
    products: {
        type:[],
        required: false,
    }
}, { timestamps: true })

export default mongoose.model("User", UserSchema)

Solution

  • have you tried addToSet()

    await User.findOneAndUpdate({email: req.body.email}, { $addToSet: { products: 
    newProduct }})
    

    here is link for doc https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.addToSet()