β

Answer by zangw for checking if an array contains

User zangw - Stack Overflow 42 阅读

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);   
作者:User zangw - Stack Overflow
most recent 30 from stackoverflow.com
原文地址:Answer by zangw for checking if an array contains , 感谢原作者分享。

发表评论