[英]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. 假设我想通过用户_id查找用户,并检查“喜欢”值(数组)是否包含某个帖子_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?
可以仅将这些_id存储在数组中,还是mongodb约定更喜欢将其他内容存储为对其他文档的引用?
So I just want to check if the user has the post _id in the "liked" array. 所以我只想检查用户是否在“喜欢的”数组中有帖子_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}
});
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 要在
liked
数组中检查4
用户名aa
> 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?
可以仅将这些_id存储在数组中,还是mongodb约定更喜欢将其他内容存储为对其他文档的引用?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.