madu
madu

Reputation: 5450

Accessing entries of an array in MongoDB with Mongoose

I have the following Schema:

var userSchema = mongoose.Schema({

    local            : {
        email        : String,
        password     : String,
        movies       : [{
                          moviename   : String,
                          rating      : Number
                        }],
    }

});

My questions are:

Can I save entries to the one after the other. I.e. can I save movies sequentially, and not all the movies (array entries) at the same time? In other words, can the movies array grow dynamically?

What I am trying to do is:

user.movies = { moviename  : "Top Gun",
                rating     : 80};
user.save(function (err) {
                    if (err)
                        console.log("Error in saving");

                    res.end(0);
                });

I believe the saving is working as I get not errors, but I'm lost at how to retrieve the entries in the array. Could someone please give me an example or a reference how to access the entries. Also, any other reference about the limitations, such as duplicate array entries (same movie).

Thank you.

Upvotes: 0

Views: 65

Answers (1)

Andrei Beziazychnyi
Andrei Beziazychnyi

Reputation: 2917

Yes, you could add movies one by one.

1) You could add movie without retrieving item at all:

userSchema.findOneAndUpdate({_id:...},
                            {$push:{"local.movies":
                                   {movieName:"movie Name", rating:5}}},
                             {'new':true}, function(err,doc){ ... })

2) Using mongoose you could retrieve item, add movie and save:

user.local.movies.push({ moviename  : "Top Gun", rating     : 80});
user.save(function (err) {
                if (err)
                    console.log("Error in saving");

                res.end(0);
            });

Regarding accessing movies array, according your schema if you retrieve user doc, you could use user.local.movies to access movies

Upvotes: 1

Related Questions