简体   繁体   中英

Mongoose - how to determine whether a nested object already exist in a query?

My database stores a User , which has an array of watchMovies[] containing a nested object movie .

When receiving an update/put API request, containing a watchedMovie object, I want to check whether the movie with id = zzz already exist in the watchedMovie[] array .

The problem is, this query doesn't do it. What am I doing wrong?

User.find(
  { username: req.params.username, 'watchedMovies.movie.id': movie.id },
  function (err, count) { 
    if (!err) exist = true;
  }
);  

Full code below:

Schema

var userSchema = new Schema({
    username: { type: String, require: true },
    firstName: String,
    lastName: String,
    ...
    watchedMovies : [{ 
        movie: { type: Schema.Types.ObjectId, ref: 'Movie' },
        time: Date,
        watchedDuration: Number,
    }],
})

JSON request body

{
    "id": "10-things-i-hate-about-you", //movie id
    "time": "2012-05-29T17:57:30.169Z",
    "watchedDuration": "88"
}

Mongoose query

router.put('/:username/watchedMovies', function (req, res, next) {

  //find movie
  Movie.findOne({ id: req.body.id }, function (err, movie) {

    if (err) res.send(err);

    //find if user already has the movie in the watchedMovies list
    var exist = false;
    User.find(
      { username: req.params.username, 'watchedMovies.movie.id': movie.id },
      function (err, count) { 
        if (!err) exist = true;
      }
    );   

    //if movie is already in watchedList, update User with it
    if (exist) {
      //set existing watchedMovie object
      User.update(...$set...)
    } else { // push new
      User.findOneAndUpdate(...$push...) 
    }

  });

});

i think this is problem , this is your model

var userSchema = new Schema({
    username: { type: String, require: true },
    firstName: String,
    lastName: String,
    ...
    watchedMovies : [{ 
        movie: { type: Schema.Types.ObjectId, ref: 'Movie' },
        time: Date,
        watchedDuration: Number,
    }],
})

but your query is

{ username: req.params.username, 'watchedMovies.movie.id': movie.id }

dont use movie.id

try this

{ username: req.params.username, 'watchedMovies.movie': movie.id }

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