简体   繁体   中英

How to find if an item exists in an array of a document mongoose

So I have queried a specific document by email from mongoose. The document has an Array called favoriteMovies . I want to now query the favoriteMovies Array and check if an item exists in there.

const user = new User({
    name: "bob",
    username: "champion",
    email: userEmail,
    favoriteMovies: [
        "Spider-Man: Far from Home",
        "logan",
        "Scarface",
        "Avengers"
    ],
    watchList: [],
    ratedMovies: []
});

Here is my query and it returns the entire Array, which is not the behavior I want.

User.find({ email: userEmail }, { favoriteMovies: "Joker" }, function (err, result) {
    console.log(err);
    console.log(result);
})

How would I find if an element is in the favoriteMovie array and possibly return true of the movie itself?

If you just need to check whether document matching the query is present, then you can use countDocument function

User.countDocuments({favoriteMovies: "Joker"}, (err, count) => {
  if (err) console.log(err);
  else {
    console.log(count);
  }
});

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