12

私は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 }
    });

ありがとう

4

2 に答える 2

12

Mongooseを使用すると、場合によっては文字列をIDとして強制的にキャストする必要があります。通常、これは自動的に行われますが、特定のケースではそうではありません。次のコードスニペットは、渡されたIDを含むすべての接続を取得します。

var mongoose = require('mongoose');
Node.find({ connections: mongoose.Types.ObjectId("535c5c1b8aa6dc5f021e8a98") }, function (err, results) { 
    console.log(results); 
});
于 2014-04-28T20:51:07.257 に答える
0

何が起こっているのかというと、Mongooseは、スキーマで定義されているように、ObjectIdへの呼び出しでcategories値に使用している値をキャストしているということです。ただし、照合しようとしているドキュメントの値はObjectIdではなく文字列型であるため、照合されません。Product.findcategoriescategories

物事を再び機能させるには、定義したスキーマと一致するように既存のドキュメントをクリーンアップする必要があります。

于 2012-09-16T23:26:45.157 に答える