node.js - 填充单个嵌入式文档

标签 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 的方式有问题,但我我想不通

最佳答案

我发现 Address 以一种无助于 populate 方法检索 的方式保存在 user 文档中>国家

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

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

但改成这种形式就解决了问题:

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

关于node.js - 填充单个嵌入式文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51518883/

相关文章:

javascript - 如何更新 Mongo 文档数组内的对象(在特定索引处)

javascript - ExpressJS : how to use authentication function in another file attached to server. js?

javascript - 如何在没有 MongoDb 的情况下使用 Parse 服务器?

mongodb - 从 ASP.NET Core 以字符串形式返回 ObjectID

mongodb - 全文检索 MongoDB/Mongoengine

有条件的MongoDB聚合框架项目

linux - npm 包未在 Linux 上执行

node.js - Express - res.send() 工作一次

node.js - 同时 Mongo 插入是否有限制

node.js - React 中的 Axios 400 错误请求