在nodejs和mongodb中填充查询

时间:2017-07-18 14:18:42

标签: node.js mongodb

我有2个产品和产品价格的集合。在产品集合中,有一个名为product_id的字段,该字段位于String中,同一字段位于productprice集合中,其名称与String相同。我如何为此决定Schema以及如何使用它来填充哪个产品带有产品价格。

产品字段:_id,Product_id,name

产品价格字段:

 _id,Product_id,price

两个集合的Product_id中的值相同。

const productpriceSchema = mongoose.Schema({
    Product_id: {
        type: mongoose.Schema.ObjectID,
        ref: 'Product'
    },
    price: String
});

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')
}

2 个答案:

答案 0 :(得分:0)

 def grailsApplication = Holders.grailsApplication

答案 1 :(得分: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的填充虚拟部分。