简体   繁体   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 . 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.我尝试使用 $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
}

In the categoryschema i have categoryname and productsCategory contains all the products that this category has.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);

In the productSchema one of it's properties is productCategory which it references to the categorySchemaproductSchema中,它的一个属性是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);

You can try it this way, assuming we're using an async function for the sake of simplicity to avoid.then.catch painful process:您可以尝试这种方式,假设我们使用异步 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

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:如果您的意思是 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.

相关问题 使用 express node.js 更新数据时出现错误 - i am getting an error while i am updating my data using express node.js 为什么我在安装节点 js 时收到此错误 - why i am getting this error while installing node js 我正在尝试将node js应用程序部署到heroku,但是在推送到master时仍然出现错误 - I am trying to deploy my node js app to heroku but I keep getting an error when pushing to master 将我的项目上传到 Heroku 时出现此错误。 我正在使用 MapBox 和 node.js - I am getting this error while uploading my project to Heroku. I am using MapBox and node.js UnhandledPromiseRejectionWarning:未处理的承诺拒绝错误,我正在使用 Node JS 和 mongo Db - UnhandledPromiseRejectionWarning: Unhandled promise rejection error I am getting I am using Node JS and mongo Db 我在使用 nodemailer 时遇到错误 - i am getting error while using nodemailer 在将无服务器节点 js 的数据保存到 mongoDB 时,我收到一个错误:-ObjectParameterError: Para obj" to Document() must be an object, - while saving data form serverless node js to mongoDB, i am getting an error:-ObjectParameterError: Para obj" to Document() must be an object, 为什么我的节点 JS 应用程序出现 Invalid shorthand property initializer 错误? - Why am I getting an Invalid shorthand property initializer error on my node JS app? 我是 node.js 的新手。在编写代码时,我在 config= 处收到语法错误意外标识符 - I am new to node.js.while writing a code iam getting an syntax error unexpected identifier at config= 从 Node JS 获取 API 时出现 CORS 错误 - I am getting CORS error while fetching API from Node JS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM