Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

node.js - How do I filter an array of objects with MongoDB Object IDs based on another array of Object IDs?

I have an array of movies pulled from MongoDB, named movieList:

[
  {
    movie: {
      _id: 5fde62aa0cec1598fda103ac,
      title: 'Wander'
    },
    status: 2
  },
  {
    movie: {
      _id: 5fde62930cec1598fd9d426c,
      title: 'Mulan'
    },
    status: 1
  },
  {
    movie: {
      _id: 5fde62a10cec1598fd9f9222,
      title: 'Greenland'
    },
    status: 0
  }
]

And I have an array of movie Object IDs (not strings), named removeMovies:

[
  5fde62a20cec1598fd9fa275,
  5fde62a30cec1598fd9fec86,
  5fde62a50cec1598fda034cf,
  5fde62a50cec1598fda03f24,
  5fde62930cec1598fd9d426c
]

The way that I would normally filter (if these were strings or numbers, as opposed to Object IDs) returns an empty array:

const filteredMovieList = movieList.filter((movie) => {
  return removeMovies.includes(movie.movie._id)
})

Any ideas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would think you can use toString and map the removeMovies objects to those strings first:

const filteredMovieList = movieList.filter((movie) => {
  return removeMovies
    .map(movieId => movieId.toString())
    .includes(movie.movie._id.toString())
})

Looking more closely as https://docs.mongodb.com/manual/reference/method/ObjectId/, I think you could use str property also.

const filteredMovieList = movieList.filter((movie) => {
  return removeMovies
    .map(movieId => movieId.str)
    .includes(movie.movie._id.str)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...