如何将字符串推入空数组

时间:2017-10-25 06:20:55

标签: javascript arrays push

当我尝试将字符串推入空数组时,我遇到了一些问题。我在下面粘贴了我的代码片段。有人可以帮我检查一下,然后告诉我哪里做错了吗? 非常感谢你。 这是我的git存储库:https://github.com/zymethyang/NodeJs_HKUST你可以帮我查一下吗? conFusionServer文件夹中的Express服务器,MongoDB中的数据库和conFusion-Angular4是webview。用户名是管理员,密码:1234。

.post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
    Favorites.findOne({ user: req.user._id })
        .then((favorite) => {
            var dishId = req.params.dishId;
            if (favorite != null) {
                if ((favorite.dishes.indexOf(dishId)) < 0) {
                    favorite.dishes.push(dishId);
                }
                favorite.save()
                    .then((favorite) => {
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'application/json');
                        res.json(favorite);
                    }, (err) => next(err));
            } else {
                favorite.dishes.push(dishId);
                favorite.save()
                .then((favorite) => {
                    res.statusCode = 200;
                    res.setHeader('Content-Type', 'application/json');
                    res.json(favorite);
                }, (err) => next(err));
            }
        }, (err) => next(err))
        .catch((err) => next(err));
})

2 个答案:

答案 0 :(得分:0)

使用下面的评论处理错误。

.post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
    Favorites.findOne({ user: req.user._id })
        .then((favorite) => {
            var dishId = req.params.dishId;
            if (favorite != null) {

                // Please handle error with initial variable.
                if (!favorite.dishes) { favorite["dishes"] = []; }

                if ((favorite.dishes.indexOf(dishId)) < 0) {
                    favorite.dishes.push(dishId);
                }
                favorite.save()
                    .then((favorite) => {
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'application/json');
                        res.json(favorite);
                    }, (err) => next(err));
            } else {

                // Please handle error with initial variable.
                favorite["dishes"] = [];

                favorite.dishes.push(dishId);
                favorite.save()
                .then((favorite) => {
                    res.statusCode = 200;
                    res.setHeader('Content-Type', 'application/json');
                    res.json(favorite);
                }, (err) => next(err));
            }
        }, (err) => next(err))
        .catch((err) => next(err));
})

答案 1 :(得分:0)

您可以通过调用

来检查元素是否为数组
if (favorite != null) {
    if (favorite.dishes != null && Array.isArray(favorite.dishes)) {
        favorite.dishes.push(value)
    } else {
        favorite.dishes = [value]
    }
}