Moongose 数组索引未完成运行



我正在尝试使用猫鼬数组索引来检查id是否在另一个模式的引用对象数组中。

下面是架构。猫鼬阵列是盘子。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var favoriteSchema = new Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    dishes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Dish'
        }
    ]
}, {
    timestamps: true
});
var Favorites = mongoose.model('Favorite', favoriteSchema);
module.exports = Favorites;

问题岌岌可危

if (favorites.dishes.indexOf(mongoose.Types.ObjectId(req.params.dishId)) === -1){

该线路在以下快速路由器中

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var authenticate = require('../authenticate');
const cors = require('./cors');
const Favorites = require('../models/favorite');
const Dishes = require('../models/dishes');
const favoriteRouter = express.Router();
favoriteRouter.use(bodyParser.json());
favoriteRouter.route('/:dishId')
.post(authenticate.verifyUser, (req, res, next) => {
    if(mongoose.Types.ObjectId.isValid(req.params.dishId)) {
        //Dishes.findById(mongoose.Types.ObjectId(req.params.dishId))
        Dishes.findById(req.params.dishId)
        .then((dish) => {
            if (dish != null) {
                //console.log("dish: ", dish);
                Favorites.findOne({user: req.user._id})
                .then((favorites) => {
                    //console.log("favorite: ", favorites);
                    if (favorites != null){
                        //favorites = favorites[0];
                        console.log("**1", favorites.dishes);
                        if (favorites.dishes.indexOf(mongoose.Types.ObjectId(req.params.dishId)) === -1){
                            console.log("**1");
                            favorites.dishes.push(req.params.dishId);
                            favorites.save()
                            .then((favorites) => {
                                res.statusCode = 200;
                                res.setHeader('Content-Type', 'application/json');
                                res.json(favorites);
                            }, (err) => next(err))
                            .catch((err) => next(err));
                        } //Error not returned if it is already in the list.
                    }else{
                        Favorites.create({user: req.user._id})
                        .then((favorites) => {
                            favorites.dishes.push(mongoose.Types.ObjectId(req.params.dishId));
                            favorites.save()
                            .then((favorites) => {
                                res.statusCode = 200;
                                res.setHeader('Content-Type', 'application/json');
                                res.json(favorites);
                            }, (err) => next(err))
                        }, (err) => next(err))
                        .catch((err) => next(err));
                    }
                }, (err) => next(err))
                .catch((err) => next(err));
            }else {
                err = new Error('Dish ' + req.params.dishId + ' is not in the database.');
                err.status = 404;
                return next(err);
            }
        }, (err) => next(err))
        .catch((err) => next(err));
    }else{
        err = new Error('Dish ' + req.params.dishId + ' is not in the database.');
        err.status = 404;
        return next(err);
    }
});
module.exports = favoriteRouter;

如何解决 issu?

你不需要 objectId 的强制转换,这样做是这样的

favorites.dishes.indexOf(req.params.dishId === -1)

如果你想返回一个错误,如果它已经存在,你应该添加一个 else 块,抛出错误。

此外,我建议您可以使用async/await语法编写代码,它将比嵌套承诺干净得多。

https://javascript.info/async-await