简体   繁体   中英

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

Let's say I want to look up a user by their _id and check if the "liked" value (array) contains a certain post _id. How do I query the db for this action? Is it okay to just store these _id's in an array or does mongodb convention prefer something else to store as a reference to other documents?

So I just want to check if the user has the post _id in the "liked" array.

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

Here is how I think this might look:

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

For the user data

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

To check the user name aa with 4 in liked array

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

but

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

No matched result.


Is it okay to just store these _id's in an array or does mongodb convention prefer something else to store as a reference to other documents?

Mongoose population could do that, you can define the user schema as below

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

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