[英]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.所以我从mongoose查询了email的具体文档。 The document has an Array called
favoriteMovies
.该文档有一个名为
favoriteMovies
的数组。 I want to now query the favoriteMovies
Array and check if an item exists in there.我现在想查询
favoriteMovies
数组并检查其中是否存在项目。
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?我如何找到一个元素是否在 favoriteMovie 数组中并可能返回电影本身的 true?
If you just need to check whether document matching the query is present, then you can use countDocument
function如果您只需要检查是否存在与查询匹配的文档,则可以使用
countDocument
function
User.countDocuments({favoriteMovies: "Joker"}, (err, count) => {
if (err) console.log(err);
else {
console.log(count);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.