填充单个嵌入式文档

时间:2018-07-25 12:26:37

标签: node.js mongodb mongoose

我有一个user模型,其中包含一个嵌入式文档address,其定义如下:

let userSchema = new Schema({
  id: ObjectId,
  //...
  address: {
    type: AddressSchema,
    required: true,
    default: () => ({})
  },
  //...
});
const UserModel = mongoose.model('User', userSchema);

Address包含一个Country模型的参考:

let AddressSchema = new Schema({
  country: {
    type: Schema.Types.ObjectId,
    ref: 'Country'
  }
});
const AddressModel = mongoose.model('Address', AddressSchema);

Country的定义是:

let countrySchema = new Schema({
  id: ObjectId,
  name: {
    type: String,
    required: true,
    unique: true
  }
});
const CountryModel = mongoose.model('Country', countrySchema);

这就是我填充用户文档的方式:

  let user = await UserModel
    .findByIdAndUpdate(
      someId,
      operators,
      { new: true }
    )
    .populate({
      path: 'address.country',
      model: CountryModel
    })

当我运行console.log(JSON.stringify(user.address))时,无法很好地获取对象,正如您可能在下面的代码注释中看到的那样,还有一个附加的_id字段,我不知道该如何摆脱:

  {
   "country":{
      "_id":{// ============> How to get rid of this _id field?
         "_id":"5b56ecab8cba833c28e0e613",
         "name":"USA",
         "__v":0
      }
   }

我使用populate方法的方式或将Address模式嵌入User的方式都有问题,但我无法弄清楚

1 个答案:

答案 0 :(得分:0)

我发现@Override public void uiDecisionSetDefaultAttributes() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); attrCatAry.add("SUBJECT"); attrTypeAry.add("INTEGER"); attrIdAry.add("com.axiomatics.seniority"); Integer userId = null; try { userId = userRepository.findByEmail(auth.getName()).getSeniority(); } catch (Exception e) { log.info(e.toString()); } attrValAry.add(userId); } 被保存在Address文档中,这种方式不利于user方法检索populate

我用来在用户中保存地址的JSON是这样的:

country

但是将其更改为这种形式可以解决问题:

{
  // Other fields of the user
  address: {
    country : {
      _id: "5b56ecab8cba833c28e0e613"
    }
  }
}