繁体   English   中英

在nodejs和mongodb中填充查询(使用mongoose)

[英]Populate query in nodejs and mongodb (using mongoose)

我有2个产品和产品价格的集合。 在产品集合中,有一个名为product_id的字段,该字段位于String中,而在productprice集合中,该字段的名称与String相同。

我如何为此确定方案,以及如何使用字段将其作为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
});

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

有关详细信息,请检查猫鼬人口的“填充虚拟对象”部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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