2017-07-18 8 views
0

私は文字列と同じフィールドにあるのproduct_idという名前のフィールドがあり、製品と製品price.Inの生成物収集のための2つのコレクションを持っているが、同じ名前でproductpriceコレクションにあり、どのように移入を使用しますどの製品にはproductpriceというフィールドが付いています。 製品フィールドは= _id、Product_id、nameです。 製品価格の項目は= _id、Product_id、priceです。 両方のコレクションで同じ値がProduct_idにあります。 const productpriceSchema = mongoose.Schema({ Product_id: { type: mongoose.Schema.ObjectID, ref: 'Product' }, price: String });nodejsとmongodbにpopulateクエリを使用する方法は? String.Howが、私はこのためにスキーマを決めることができるよう

const productSchema = mongoose.Schema({ Product_Name: type: String, User_Object_ID :type: String, cid :type: String });

const Product = module.exports = mongoose.model('Product', productSchema);

const Productprice = module.exports = mongoose.model('Product_price', productpriceSchema);

module.exports.productwithprice = function(callback,limit){ Productprice.find({}, callback).populate('Product_id') }

答えて

0
//Product Schema 
//you don't have to give field _id, mongodb will automatically generate it. 
const productSchema = new Schema({ 
    Product_Id: String, 
    name: String 
}); 

const Product = mongoose.model('Product', productSchema); 

//Product Price Schema 

const productPriceSchema = new Schema({ 
    Product_Id: { 
     type: Schema.ObjectId, 
     ref: 'Product' 
    }, 
    price: String 
}); 

const ProductPrice = mongoose.model('ProductPrice', productPriceSchema) 

ProductPrice.find({query}) 
.populate('Product_Id') 
.exec((err, products) => { 
    //Logic 
}); 
+0

このクエリは機能しません。私の製品のコレクションで_idは「_id」の形式である:私はproductpriceコレクションのPRODUCT_IDと一致させたいのObjectId(「595f4cb77e713872c1297941」)、「595f4cb77e713872c1297941」。これで私を助けてください。 –

+0

コードを投稿してください。 – sohamdodia

+0

上記のコードを提出しました。 –

0
var ProductSchema = new Schema({ 
    name: String, 
    productId: String 
}); 

var PriceSchema = new Schema({ 
    name: String, 
    productId: String 
}); 

ProductSchema.virtual('price', { 
    ref: 'Price', // The model to use 
    localField: 'productId', // Find price where `localField` 
    foreignField: 'productId', // is equal to `foreignField` 
    // If `justOne` is true, 'price' will be a single doc as opposed to 
    // an array. `justOne` is false by default. 
    justOne: true 
}); 

var Product = mongoose.model('Product ', ProductSchema); 
var Price = mongoose.model('Price ', PriceSchema); 

Product.find({}).populate('price').exec(function(error, products) { 
    /* `products.price` is available now */ 
}); 

詳細については、確認してください移入バーチャセクションはMongoose populationです。

+0

このクエリは、既定のエンジンが指定されておらず、拡張機能が提供されていないというエラーを表示します。 –

+0

このエラーは、エクスプレスのレンダリングエンジンについて、mongooseに関連していないものと思われます。エクスプレスコードを確認してください。 – subaru710

関連する問題