我正在尝试使用Mongoose数组indexOf来检查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;
我该如何解决问题?
答案 0 :(得分:2)
您不需要强制转换objectId,就像这样
favorites.dishes.indexOf(req.params.dishId === -1)
如果要返回已存在的错误,则应添加else块以引发错误。
我还建议您可以使用async/await
语法编写代码,它比嵌套的Promise干净得多。