简体   繁体   中英

Populate query in nodejs and mongodb (using mongoose)

I have 2 collections for product and product price. In product collection there is a field named product_id which is in String and the same field is in productprice collection with the same name as String.

How can I decide Schema for this and how to populate for which product comes with a field as productprice with it?

product fields : _id,Product_id,name

Product price fields :

 _id,Product_id,price

where the same value is in Product_id for both the collections.

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')
}
//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
});
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 */
});

For detail, please check Populate Virtuals section of Mongoose population .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM