如何解决从猫鼬中获取与数据无关的数据
从与猫鼬没有任何关系的不同集合中获取数据
集合模式
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,skills: ['HTML','PHP'],// skill id
Education: [ 5f453e7f53895727f0e39d82,location: 'India'
} ```
解决方法
您可以使用aggregate(),
- $lookup加入
skill
集合,匹配技能集合中的技能 - $addFields使用$reduce 以数组格式添加技能名称
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,这是未经测试的代码!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。