Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mongodb query doesn't work

Mongodb query doesn't work

Problem

In my image sharing application you can upload images and create Albums. When you delete an image from the site it shall also be deleted in the albums (the ones that has got the image in it).

Below is the route for deleting an image, and what I really need help with is why the Code for deleting the images (imageName and imageId) in the albums below doesn't work.

Thanks in advance!

The models:

var AlbumSchema = new Schema({
      title             : String,
      imageName         : [String],
      imageId           : [String]
});

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

-

var BlogPostSchema = new Schema({
    name : String,
    size : Number,
    type : String,
    author : ObjectId,
    title   : String
});

modelObject.Comment = mongoose.model('Comment', CommentSchema);
modelObject.BlogPost = mongoose.model('BlogPost', BlogPostSchema);

The part that doesn't work in the code below is the following:

albums[i].imageName.remove(j);
albums[i].imageId.remove(j);                            
albums[i].save(function (err){
    if (err) {
        console.log(err);
        // do something
    }
});

Full code:

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

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

        var theImage = blog.name;

        var query = albumModel.Album.find( { imageName:theImage } )
        query.exec(function (err, albums) {

            if (!albums) {

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

                res.redirect('/blogs');

            }

            else {
                for (var i = 0; i 
Problem courtesy of: holyredbeard

Solution

JavaScript arrays don't have a remove method so I would expect your code may be crashing. You should be using code like albums[i].imageName.splice(j, 1); instead.

Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Mongodb query doesn't work

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×