简体   繁体   中英

Mongoose query find 'string' in object field in array of objects

My model looks like this:

Collection = new Schema({
 name: {type: String, required: true},
 tags: [String],
 movies: [{_id: false,
          original_title: {type: String}}]
)};

I need to alter the following query to use 'req.body' (an array of strings) to not only find a match in the 'tags' array but also find match(es) with the 'original_title' field in the movies array.

Collection.find({'tags' : { $in : req.body}}, (err, collections) => {           
            if(err){res.status(400).json(err);}

            if(!collections)
            {
                res.status(404).json({message: 'No collections found'});
            }else{
                res.json(collections);
            }
        }).limit(8);

Try this:

db.collection.find({
    $or: [{
            'tags': {
                $in: req.body
            }
        },
        {
            'original_title': {
                $in: req.body
            }
        }
    ]
}, (err, collections) => {
    if (err) {
        res.status(400).json(err);
    }

    if (!collections) {
        res.status(404).json({
            message: 'No collections found'
        });
    } else {
        res.json(collections);
    }
}).limit(8);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM