首页 文章

检查数组是否包含mongodb文档中的post id

提问于
浏览
0

假设我想通过他们的_id查找用户并检查“喜欢”值(数组)是否包含某个帖子_id . 如何查询数据库以执行此操作?是否可以将这些_id存储在数组中,或者mongodb约定是否更喜欢将其他内容存储为其他文档的引用?

所以我只想检查用户是否在“喜欢”数组中有post _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
  });
}

1 回答

  • 3

    对于用户数据

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

    liked 数组中检查用户名 aa4

    > 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约定更喜欢将其他内容存储为其他文档的引用?

    Mongoose population可以这样做,你可以定义如下的用户模式

    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);
    

相关问题