使用mongodb 3.4到MEAN,我有两个模式:
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true },
username: {
type: String,
unique: true,
required: true,
trim: true },
password: {
type: String,
required: true }
},
{ collection: 'users'}
);
module.exports = mongoose.model('User', userSchema);
和另一个:
var followSchema = new mongoose.Schema({
username: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
followers: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
following: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},{ collection: 'follows'}
);
module.exports = mongoose.model('Follow', followSchema);
当用户A有关注者并且跟随以下内容时,在下面的对象中产生(作为例子):
{
"_id" : ObjectId("ae1d6f8..."),
"username" : ObjectId("User A"),
"followers" : [
ObjectId("User B")
ObjectId("User C")
],
"following": [
ObjectId("User B")
]
}
我想检索所有关注者的用户名并关注。我不工作的查询是:
Follow.aggregate([{
$match: {
"username": user_id
}
},
{
$lookup: {
"from": "User",
"localField": "following",
"foreignField": '_id',
"as": "userFollowing"
}
},
{
$lookup: {
"from": "User",
"localField": "followers",
"foreignField": '_id',
"as": "userFollowers"
}
}, {
$project: {
"username": 1,
"userFollowers": 1,
"userFollowing": 1
}
}
]).exec(function (err, doc) {
console.log(doc);
rest.json({
'state': true,
'msg': 'Follow list',
'doc': doc
})
})
这个空数组的结果以下是& userFollowers:
[ { _id: 5aeca47e600ff8f00617ac05,
username: 5ae1ee337863273c0adac1d7,
userFollowing: [],
userFollowers: [] } ]
感谢您的帮助。