我在MongoDB中有这个项目:
[
{
title: 'Product Name',
_id: 5052843e023273693300013c,
description: 'This is a fake description',
categories: [ 5052843e023273693300010a ],
}
]
我想找到像这样具有此类别的产品。 我已尝试过:
Product.find({ categories: mongoose.Types.ObjectId('5052843e023273693300010a')})
Product.find({ categories: mongoose.mongo.BSONPure.ObjectID.fromString('5052843e023273693300010a')})
Product.find({ categories: '5052843e023273693300010a'})
Product.find({ 'categories': '5052843e023273693300010a'})
Product.find({ categories: {$in: ['5052843e023273693300010a']}})
Product.find({ categories: Schema.Types.ObjectId('5052843e023273693300010a')})
但是什么都不起作用。我可以使用以下方式通过id进行获取:_id: '5052843e023273693300013c'。请注意,当插入产品时,类别ID被添加为字符串(这意味着我只是分配了ID而不是类别对象,但这并不能解释为什么上述任何内容都不起作用 - 在转储中未引用,因此Mongo可能将其识别为对象ID。
类似的SO问题没有得到答案。
我正在使用最新的Mongoose(3个版本)和最近的Mongo、Node。
更新:
我可以使用CLI轻松获取:
db.products.find({ categories: '5052843e02327369330000fe' });
有趣的是,我可以通过在代码中使用不等于符号来获取它 - 哦?
Product.find({ categories: { $ne: '5052843e02327369330000fe' }})
我的架构如下:
var Product = new Schema({
title: { type: String, required: true },
slug: { type: String },
summary: { type: String }, //browser title
description: { type: String, required: false },
excerpt: { type: String }, //for a list and also for the meta description
publish: { type: Boolean },
featured: { type: Boolean },
unavailable: { type: Boolean },
model: { type: String },
google: { type: String },
tags: { type: Array },
categories: [{ type: Schema.Types.ObjectId, ref: 'Category' }],
manufacturer: { type: String },
variations: { type: Array },
prices: { type: Array },
images: { type: Array },
specs: { type: Array },
modified: { type: Date, default: Date.now }
});
var Category = new Schema({
title: { type: String, required: true },
description: { type: String },
parent: { type: Schema.Types.ObjectId, ref: 'Category' },
images: { type: Array }
});
谢谢。
Product
模型的架构定义是什么? - JohnnyHK