检查数组是否在MongoDB文档中包含帖子ID

checking if an array contains a post id in a mongodb document

本文关键字:包含帖 ID 文档 MongoDB 数组 是否 检查      更新时间:2023-09-26

假设我想通过用户的_id查找用户并检查"liked"值(数组)是否包含某个帖子_id。如何查询数据库以获取此操作?是否可以将这些_id存储在数组中,或者 mongodb 约定更喜欢其他东西作为对其他文档的引用进行存储?

所以我只想检查用户是否在"喜欢"数组中_id了帖子。

var users = new mongoose.Schema({
  name       : {type: String, unique : true, required : true, dropDups: true},
  password   : {type: String, required : true}, //hash
  liked      : [String],
  created    : {type: Date, default: Date.now}
});                 

以下是我认为这可能的样子:

function checkIfLiked() {
  let uname  = "Jim";
  let postId = "abc";
  //check if $USER has `postId` in $LIKED
  user.findOne({$USER: uname},{$LIKED: {$in: postId} }, function(err, results) {
    //do something after check
  });
}

对于用户数据

{ "_id" : ObjectId("56effca6e668e15e2eaa6dfe"), "liked" : [ "11", "23", "4" ], "name" : "aa" }
{ "_id" : ObjectId("56effcb1e668e15e2eaa6dff"), "liked" : [ "1", "2", "3" ], "name" : "bb" }

使用数组中的4检查用户名aa liked

> db.user.find({liked: '4', name: 'aa'})
{ "_id" : ObjectId("56effca6e668e15e2eaa6dfe"), "liked" : [ "11", "23", "4" ], "name" : "aa" }

> db.user.find({liked: '2', name: 'aa'})

没有匹配的结果。


是否可以将这些_id存储在数组中,或者 mongodb 约定更喜欢存储其他内容作为对其他文档的引用?

猫鼬种群可以做到这一点,您可以定义用户架构,如下所示

var users = new mongoose.Schema({
  name       : {type: String, unique : true, required : true, dropDups: true},
  password   : {type: String, required : true}, //hash
  liked      : [{ type: Schema.Types.ObjectId, ref: 'User' }],
  created    : {type: Date, default: Date.now}
});    
var User = mongoose.model('User', users);