首页 > 解决方案 > Mongoose,推送一个数组 Model.update 不是函数

问题描述

猫鼬类别架构:

    const CategoryAdvertSchema = new mongoose.Schema({
        UniqueHomes: {
            cave: { type: Boolean, default: false },
            natureLodge: { type: Boolean, default: false },
            castle: { type: Boolean, default: false },
            farmStay: { type: Boolean, default: false }
        },
        PropertyType: {
            apartment: { type: Boolean, default: false },
            villa: { type: Boolean, default: false },
            loft: { type: Boolean, default: false },
            yurt: { type: Boolean, default: false }
        },
        Others: [CategoryDynamiqueSchema]
    });

我的猫鼬 OthersShema 用于推送数组:

    const CategoryDynamiqueSchema = new mongoose.Schema({
        dayOfCategory: { type: Date, default: Date.now },
        nameOfCategory: { type: String },
        typeOfCategory: { type: String }
    });

我的 API:

category.post('/category', jwt.checkUserToken, (req, res) => {
    const dayOfCategory = Date.now();
    const nameOfCategory = req.body.nameOfCategory;
    const typeOfCategory = req.body.typeOfCategory;

    CategoryAdvert.update({
        $push: {
            Others: {
                dayOfCategory: dayOfCategory,
                nameOfCategory: nameOfCategory,
                typeOfCategory: typeOfCategory
            }
        }
    }, { new: true }, (err, category) => {
        if (err) {
            res.json({ success: false });
            console.log('err : ', err);
        } else {
            console.log("La catégorie '" + nameOfCategory + "' a bien été ajouté");
            res.json({ success: true });
        }
    });
});

当我尝试推送数组时,出现以下错误:

TypeError:CategoryAdvert.update 不是函数

标签: javascriptarraysnode.jsmongoosepush

解决方案


我做了一些改变,它正在工作

    category.post('/category', jwt.checkUserToken, (req, res) => {
        console.log('req.body => ', req.body);
        const dayOfCategory = Date.now();
        const nameOfCategory = req.body.nameOfCategory;
        const typeOfCategory = req.body.typeOfCategory;

        Advert.update({
            $push: {
                'CategoryAdvert.Others': {
                    dayOfCategory: dayOfCategory,
                    nameOfCategory: nameOfCategory,
                    typeOfCategory: typeOfCategory
                }
            }
        }, { new: true }, (err, category) => {
            if (err) {
                res.json({ success: false });
                console.log('err : ', err);
            } else {
                console.log("La catégorie '" + nameOfCategory + "' a bien été ajouté");
                res.json({ success: true });
            }
        });
    });

推荐阅读