【问题标题】:checking if an array contains a post id in a mongodb document检查数组是否包含 mongodb 文档中的帖子 ID
【发布时间】:2016-07-08 00:56:12
【问题描述】:

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

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

【问题讨论】:

    标签: javascript arrays node.js mongodb mongoose


    【解决方案1】:

    对于用户数据

    { "_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);   
    

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 2016-12-11
      • 2012-11-26
      • 1970-01-01
      • 2018-10-12
      • 2018-08-21
      相关资源
      最近更新 更多