首页 > 解决方案 > In mongoose, how can i check if all elements in an ObjectId Array exists on database

问题描述

Im working on a NodeJS RESTful API, using mongoose and MongoDB of course.

I have a mongoose model like this

const mySchema = mongoose.Schema({
  _id: {type: mongoose.Schema.Types.ObjectId},
  Cities: [{type: mongoose.Schema.Types.ObjectId, ref: 'City'}]

}

and a route like this

router.post('/', (req, res, next) => {
    for (const cityId of req.body.cities) {
        City.findById(cityId)
            .then(city => {
                if (!city) {
                   return routingResult.NotFound(res, "One city doesnt exists.");
                }
             })
             .catch(err => {
                 console.error(err);
                 routingResult.Error(res, err);
             });

As you can see, i'm trying to check if ALL of the elements on req.body.cities array exists on Database before i create a new document and save it.

I need to know if there's a way to check all elements at the same time. (those elements are ObjectID's that references another collection on my DB), something like City.find({"$all":req.body.cities}) ... i know this is not the proper implementation, i just want to know if there's something like that.

If any of the objectId's doesn't exists i must not create the new document to be inserted on Cities collection.

Is there a way to achieve this ?

标签: javascriptnode.jsmongodbmongoosemongoose-schema

解决方案


推荐阅读