我有一个 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/