从数组中的嵌套obj填充特定字段

时间:2019-11-13 09:34:03

标签: mongodb mongoose

const UserSchema = new Schema({
 .....,
 profile: { type: Schema.Types.ObjectId, ref: 'profile' }
});

const ProfileSchema = new Schema({
  .....,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  image: { type: Array, default: [{ secure_url: '', public_id: 0 }] },
}, { timestamps: true });

const EventSchema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  ....
});

和数据库

   "image" : [ 
    {
        "secure_url" : "",
        "public_id" : "0"
    }, 
    {
        "secure_url" : "some url here",
        "public_id" : "some long number here"
    }
],

创建事件后

   event.save()
     .then(({ _id }) => {
        Event.findById(_id)
          .populate({ path:'user', model: 'user', select: 'first_name', 
           populate: { path: 'profile', model: 'profile', select: 'image' } 
          })
         .exec((err, evt) => res.json(evt))
         })
     .catch(err => res.status(400).json({ error: 'Ooops' }));
  });

如何仅返回图像中的第一个obj?将public_id设置为0的那个? 否则,它将返回图像数组中的所有obj 谢谢

0 个答案:

没有答案