私はmongoにこのアイテムを持っています:
[ { 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: '5052843e023273693300013c'を使用して、idで問題なくフェッチできます。
製品が挿入されたときに、カテゴリ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 list and also for 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 }
});
ありがとう