gpt4 book ai didi

javascript - Mongoose - 如何确定查询中是否已存在嵌套对象?

转载 作者:行者123 更新时间:2023-11-28 05:57:43 27 4
gpt4 key购买 nike

我的数据库存储一个User,它有一个watchMovies[]数组,其中包含一个嵌套对象movie

当收到包含 watchedMovie 对象的 update/put API 请求时,我想检查 movie 是否具有 id = zzz 已存在于 watchedMovie[] 数组中。

问题是,这个查询没有做到这一点。我做错了什么?

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

完整代码如下:

架构

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 请求正文

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

Mongoose 查询

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...)
}

});

});

最佳答案

我认为这是问题,这是你的模型

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,
}],
})

但是您的查询是

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

不要使用movie.id

试试这个

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

关于javascript - Mongoose - 如何确定查询中是否已存在嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37513712/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com