[英]Mongoose: Query by subdocument ObjectId attribute
I have the following query:我有以下查询:
Stuff.findOneAndUpdate({ status: 'open', ...query }, value, { new: true });
where query
is: { 'buyer.user': mongoose.Types.ObjectId(user._id) }
;其中
query
是: { 'buyer.user': mongoose.Types.ObjectId(user._id) }
;
As you can see, my Stuff
model has a subdocument buyer
, that has a user
attribute with an ObjectId
如您所见,我的
Stuff
model 有一个buyer
Buyer ,它有一个带有ObjectId
的user
属性
If I run that exact query in mongo directly it returns the result I want but, it always returns empty when using mongoose.如果我直接在 mongo 中运行该精确查询,它会返回我想要的结果,但是在使用 mongoose 时它总是返回空。
Do you have any ideas why?你有什么想法为什么?
Edit编辑
This is my schema:这是我的架构:
const StuffSchema = new mongoose.Schema(
{
items: [{ type: Donation.schema, default: [] }],
status: { type: String, default: 'open', enum: ['open', 'purchase_completed'] },
total: Number,
buyer: { type: BuyerDataSchema },
},
{ timestamps: true }
);
and和
const BuyerDataSchema = new mongoose.Schema(
{
name: { type: String, required: false },
email: { type: String, required: false },
phone: { type: String, default: '' },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
},
{ _id: false }
);
Does this help?这有帮助吗?
When you are using a ref
and want to include that subdocument into a result of query you need to call populate
functuon with the name of a field eg当您使用
ref
并希望将该子文档包含到查询结果中时,您需要使用字段名称调用populate
函数,例如
Stuff.find(...).populate("user")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.