[英]Mongoose: Query by subdocument ObjectId attribute
我有以下查询:
Stuff.findOneAndUpdate({ status: 'open', ...query }, value, { new: true });
其中query
是: { 'buyer.user': mongoose.Types.ObjectId(user._id) }
;
如您所见,我的Stuff
model 有一个buyer
Buyer ,它有一个带有ObjectId
的user
属性
如果我直接在 mongo 中运行该精确查询,它会返回我想要的结果,但是在使用 mongoose 时它总是返回空。
你有什么想法为什么?
编辑
这是我的架构:
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 }
);
和
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 }
);
这有帮助吗?
当您使用ref
并希望将该子文档包含到查询结果中时,您需要使用字段名称调用populate
函数,例如
Stuff.find(...).populate("user")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.