简体   繁体   中英

I am getting an error while i am pushing an object to the array property in node js using monogoose

My Problem is i want after i create the categoryName and then i create the product properties, then i can push the product properties to the categoryProduct field .

I tried that using $push and it gives me an empty array in the db.

CallBack Function for creating a product

//Here i am getting the values from the body

//create an object 

const productObject = new productSchema({

    productName: req.body.productName,
    productPrice: req.body.productPrice,
    productCategory: req.body.productCategory,
    productQuantity: req.body.productQuantity,
    productSection: req.body.productSection,
    productExDate: req.body.productExDate

})


    //saving 
    productObject
        .save()
        .then(data => {
            res.redirect('/halalMunchies/all-products');
        })
        .catch(err => {
            res.status(500).send({
                message: err.message || "Some error occured while creating a create operation"
            });
        });

    //pushing inside the productCategory in the category model

    categoryDB.findOneAndUpdate({ categoryName: req.body.productCategory }, { $push: { productsCategory: productObject._id } })
        .then(result => {
            console.log(result);
        })
        .catch(err => {
            console.log(err);
        })

the output

  {
  _id: new ObjectId("61a62e619c17c622153c4d1a"),
  categoryName: 'meat',
  productsCategory: [],
  __v: 0
}

In the categoryschema i have categoryname and productsCategory contains all the products that this category has. Category Schema

    var categorySchema = new mongoose.Schema({

    //properties // shape of the documentation

    categoryName: {
        type: String,
        required: true,
        unique: true

    },

    productsCategory: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'productSchema',
        required: true
    }]

});

const categoryDB = mongoose.model('categorySchema', categorySchema);

In the productSchema one of it's properties is productCategory which it references to the categorySchema

    var productSchema = new mongoose.Schema({

    //defining the properties

    productName: {
        type: String,
        unique: true,
        required: [true, 'Product name is required'] // we can pass a message like this 
    },

    productCategory: {
        type: mongoose.Schema.Types.String,
        ref: 'categorySchema',
        required: [true, 'Category name is required'] // we can pass a message like this 
    },

    productPrice: {
        type: Float,
        required: [true, 'Price name is required'] // we can pass a message like this 
    },

    productQuantity: {
        type: Number,
        required: [true, 'Quantity name is required'] // we can pass a message like this 
    },

    productSection: {
        type: String,
        required: [true, 'Section name is required'] // we can pass a message like this 
    },

    productExDate: {
        type: String,
        required: [true, 'ExDate name is required'] // we can pass a message like this 
    }


})

const productDB = mongoose.model('productSchema', productSchema);

You can try it this way, assuming we're using an async function for the sake of simplicity to avoid.then.catch painful process:

const {
  productData,
  productCategory,
} = req.body;

const productObject = new productSchema({ ...productData });

await productObject.save();

const categoryObject = await categorySchema.findOne({ categoryName: productCategory });

if (!categoryObject) {
  // Throw some error
}

await categoryObject.productsCategory.push(productObject._id);
await categoryObject.save();

// then make your redirect to /halalMunchies/all-products

EDIT

const {
  productName,
  productPrice,
  productQuantity,
  productSection,
  productExDate,
  productCategory,
} = req.body;

const productObject = new productSchema({
  productName,
  productPrice,
  productCategory,
  productQuantity,
  productSection,
  productExDate,
});

await productObject.save();

If you mean by productCategory "category id", then you should fetch by _id:

const categoryObject = await categorySchema.findOne({ _id: productCategory });

if (!categoryObject) {
  // Throw some error
}

await categoryObject.productsCategory.push(productObject._id);
await categoryObject.save();

// then make your redirect to /halalMunchies/all-products

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM