Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a match in an array field

In my image sharing application you can create albums and add images to them. When an image is deleted from the site, it should as well be removed from the album(s) that stores references to the image (name, id).

The thing I need help with is to find which albums that has stored the image (reference) that's about to be removed.

In the route below is what I've tried so far, but I get an error on the query. I've checked the Mongodb docs and the syntax looks like this:

db.collection.find( { field : { $in : array } } );

In my route the field and the array has switched places, which doesn't seem to work.

I would really appreciate some help. Thanks in advance!

My models looks like the following:

var AlbumSchema = new Schema({
      title             : String,
      imageName         : [String], <-- array the contains of images names
      imageId           : [String] <-- array the contains of images id's
});

modelObject.AlbumSchema = AlbumSchema;
modelObject.Album = mongoose.model('Album', AlbumSchema);

var ImageSchema = new Schema({
    name : String,
    size : Number,
    type : String
});

modelObject.ImgSchema = ImgSchema;
modelObject.Image = mongoose.model('Image', ImgSchema);

The route for deleting an image:

app.get('/blog/delete/:id', function(req, res){

    model.ImagePost.findById(req.params.id, function (err, blog){

        var theImage = blog.name;

        if (err) {
            console.log(err);
            // do something
        }

        var query = albumModel.Album.find( { imageName: { $in : theImage } } );

        query.exec(function (err, albums) {

            if (!albums) {
                console.log(err);
                // do something

                blog.remove(function(err) {
                    console.log(err);
                    // do something
                });

                res.redirect('/blogs');
            }

            else {
                // code for removing the image(s) in the albums

                res.redirect('/blogs');
            }
        });
    });
});
like image 205
holyredbeard Avatar asked Jun 04 '12 16:06

holyredbeard


1 Answers

db.collection.find( { field : { $in : array } } ); is not the syntax that you want. That says "Find me the document where this field has one of the list values that I'm going to give you in an array."

You want to use equality while reaching into the array.

db.collection.find( { imageName:theImage } )

This says find me the document where imageName is theImage so this will return the Album (or Albums if a picture can be in more than one album) which contains this image in its imageName array.

like image 196
Asya Kamsky Avatar answered Oct 20 '22 08:10

Asya Kamsky