繁体   English   中英

使用 monogoose 将 object 推送到节点 js 中的数组属性时出现错误

[英]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

我尝试使用 $push 并在数据库中给了我一个空数组。

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
}

categoryschema ,我有categorynameproductsCategory包含该类别拥有的所有产品。 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);

productSchema中,它的一个属性是productCategory ,它引用了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);

您可以尝试这种方式,假设我们使用异步 function 为简单起见避免.then.catch 痛苦的过程:

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

编辑

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

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

await productObject.save();

如果您的意思是 productCategory “类别 id”,那么您应该通过 _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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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