从猫鼬中获取与数据无关的数据

问题描述

从与猫鼬没有任何关系的不同集合中获取数据

集合模式

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()

db.user.aggregate([
  {
    $lookup: {
      from: "skill",localField: "skills",foreignField: "skillid",as: "skills"
    }
  },{
    $addFields: {
      skills: {
        $reduce: {
          input: "$skills",initialValue: [],in: {
            $concatArrays: [["$$this.name"],"$$value"]
          }
        }
      }
    }
  }
])

Playground


您可以使用猫鼬Virtual并查看this

// 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,这是未经测试的代码!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...