为什么$ push不添加newCategory

时间:2018-12-24 11:25:17

标签: node.js mongoose

我想将新类别推入现有类别,但没有这样做,并返回一个空数组。

我也使用.save()进行了尝试,但是并没有太大帮助。

//发布路线

Typedef uint8 x[4]

//猫鼬模式

router.post('/category', middleware.isAdmin, upload.single('category[image]'), async  function(req,res, next){
try {
    let result = await cloudinary.v2.uploader.upload(req.file.path,{  // upload image to cloudinary
     folder: 'category_images',
     use_filename: true
    }); 
    let categories = await Category.find({});
    let i = await categories.findIndex((e) => e.name === req.body.category.name); // find if category name already exits
    if(i === -1){
        let newCategory = {   //create new category name
            name : req.body.category.name,
            image : result.secure_url,
            imageId : result.public_id
        };
        // categories.push(newCategory);
        // categories.save();
        // // Category.save();

        await Category.findOneAndUpdate({_id: req.user.cart.id}, {$push: {categories: newCategory}}); // push the newCategory to existing category array
        let categories = await Category.find({});

        console.log(categories);
        req.flash('success','category added to db');
        console.log(categories);
    }
    else {
        req.flash('error', 'categorory already exits');
    }
    res.redirect('back');
}
catch(err){
    req.flash('error', err.message, err.name);
    console.log(err);
    res.redirect('back');
}
});    

我做var mongoose = require("mongoose"); var categorySchema = new mongoose.Schema ({ categories : [ { name: String, image : String, ImageId : String } ] } ); module.exports = mongoose.model('Category', categorySchema); 时返回[]

0 个答案:

没有答案