【问题标题】:Populate query in nodejs and mongodb (using mongoose)在 nodejs 和 mongodb 中填充查询(使用 mongoose)
【发布时间】:2017-12-23 11:28:46
【问题描述】:

我有 2 个产品系列和产品价格系列。在产品集合中,有一个名为product_id 的字段在字符串中,相同的字段在productprice 集合中,与字符串同名。

如何为此决定 Schema 以及如何填充带有 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')
}

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:
    //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
    });
    

    【讨论】:

    • 此查询无效。在我的产品集合中,_id 的形式为“_id”:ObjectId(“595f4cb77e713872c1297941”),我想将其与 productprice 集合的 Product_id 匹配:“595f4cb77e713872c1297941”。请帮助我。
    【解决方案2】:
    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 的填充虚拟部分。

    【讨论】:

    • 这个查询给出了一个错误,没有指定默认引擎并且没有提供扩展
    • 这个错误似乎是您的 express 渲染引擎有问题,与猫鼬无关。请检查您的快递代码。
    猜你喜欢
    • 2021-03-03
    • 1970-01-01
    • 2023-03-27
    • 2012-07-03
    相关资源
    最近更新 更多