从与猫鼬没有任何关系的不同集合中获取数据
集合模式
mongoose.Schema({
skillid:{type:Number},
name:{type:String},
});
技能收集
mongoose.Schema({
userid: {type: mongoose.Types.ObjectId},
OverView:{type:String},
location:{type:String},
skills:[{Type:Number}]
});
{
_id: 5f48d5d1b98bffee67b49917
skillid: 1
name: 'HTML'
}
{
_id: 5f48d612b98bffee67b49919
skillid: 2
name: 'PHP'
}
User Collection
{
_id: 5f425bdb311b791670d60de6,
userid: 5f41115fbd904134883ae2d8,
OverView: 'sdsdssdsd',
skills: [1,2], // skill id
Education: [ 5f453e7f53895727f0e39d82, 5f453fb963d4ab181c115982 ],
location: 'India',
}
您如何从Skill Collection-猫鼬中获得技能名称
我想要这样的结果
{
_id: 5f425bdb311b791670d60de6,
userid: 5f41115fbd904134883ae2d8,
OverView: 'sdsdssdsd',
skills: ['HTML','PHP'], // skill id
Education: [ 5f453e7f53895727f0e39d82, 5f453fb963d4ab181c115982 ],
location: 'India'
} ```
答案 0 :(得分:0)
您可以使用aggregate(),
skill
集合,匹配技能集合中的技能db.user.aggregate([
{
$lookup: {
from: "skill",
localField: "skills",
foreignField: "skillid",
as: "skills"
}
},
{
$addFields: {
skills: {
$reduce: {
input: "$skills",
initialValue: [],
in: {
$concatArrays: [["$$this.name"], "$$value"]
}
}
}
}
}
])
// SKILL SCHEMA
const SkillSchema = mongoose.Schema({
skillid:{type:Number},
name:{type:String},
});
// USER SCHEMA
const UserSchema = mongoose.Schema({
userid: {type: mongoose.Types.ObjectId},
OverView:{type:String},
location:{type:String},
skills:[{Type:Number}]
});
// CREATES VIRTUAL CONNECTION WITH SKILL COLLECTION
UserSchema.virtual('skills', {
ref: 'Skill', // The model to use
localField: 'skills', // Find people where `localField`
foreignField: 'skillid', // is equal to `foreignField`
// If `justOne` is true, 'members' will be a single doc as opposed to
// an array. `justOne` is false by default.
justOne: false,
// you can use other options
// options: { sort: { name: -1 }, limit: 5 }
});
// CREATE MODELS
const User = mongoose.model('User', UserSchema);
const Skill = mongoose.model('Skill', SkillSchema);
// QUERY TO FIND USERS AND POPULATE SKILLS
User.find({}).populate('skills').exec(function(error, user) {
console.log(user);
});
注意:如果遇到任何问题,请参考documentation,这是未经测试的代码!