简体   繁体   English

如何在Mongoose中检索存储在一对多关系中的文件

[英]How to retrieve documents stored in one to many relationship in Mongoose

I have 2 Schemas.我有 2 个模式。 Shop and Product.商店和产品。 One shop can have many products.一个商店可以有很多产品。 But I also have more than one Shop.但我也有不止一家店铺。 Let's say I have 5 shops, and each of those shops have their own products.假设我有 5 家商店,每家商店都有自己的产品。 I am able to save the products and find their IDs in the Shops respectively.我能够保存产品并分别在商店中找到它们的 ID。 But I am struggling to output products that belong to one specific shop.但是我正在努力寻找属于一个特定商店的 output 产品。 I can output each shop by their ID and see all the product IDs added.我可以通过他们的 ID output 每个商店并查看所有添加的产品 ID。 But how do I get the product name, description etc (all Product fields) of each product in a shop?但是如何获取商店中每个产品的产品名称、描述等(所有产品字段)?

My project works like this: I create a shop, then I add products to each shop by selecting the shop's ID and storing the product ID inside the shop.我的项目是这样工作的:我创建了一个商店,然后通过选择商店的 ID 并将产品 ID 存储在商店中来向每个商店添加产品。 Then in my view I want to eventually be able to select a shop and show all the products inside the shop.然后在我看来,我希望最终能够 select 一个商店,并展示商店里面的所有产品。

I am stuck on getting the rest of the fields for Products.我一直坚持获取产品字段的 rest。 I have read through the documentation?我已经阅读了文档? Maybe I am missing something.也许我错过了什么。 Please help.请帮忙。

My Product model我的产品 model

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    shopName: {
        type: String,
    },
    product: {
        type: String,
        required: true
    },
    productDescription: {
        type: String,
        required: true,
    },
    productPrice: {
        type: Number,
        required: true
    },
    inStock: {
        type: Boolean,
        required: true
    },
    totalStock: {
        type: Number,
        required: true
    },
    productImage: {
        type: Object,
        required: true,
        data: Buffer, 
        contentType: String
    }
});

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

My Shop Model:我的店铺 Model:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ShopSchema = new Schema({
    shopName: {
        type: String,
        required: true
    },
    shopImage: {
        type: Object,
        required: true,
        data: Buffer, 
        contentType: String 
    },
    shopDescription: {
        type: String,
        required: true
    },
    shopCategory: {
        type: String,
        required: true
    },
    products: [{
        type: Schema.Types.ObjectId,
        ref: 'productModel'
    }]
}, { timestamps:true });

const Shop = mongoose.model('Shop', ShopSchema);
module.exports = Shop;

My routes:我的路线:

//get all shops
//WORKS
router.get('/shops', (req, res) => {
    model.Shop.find()
        .then(result => res.render('shop/shops', { title: 'Shops', shops: result }))
        .catch(err => console.log(err));
});

//get all products
// HOW TO GET THE PRODUCT NAME, PRICE, DESCR ETC??
router.get('/products/:id', (req, res) => {
    model.Product.find()
        .then(result => res.render('shop/products', { title: 'Products View', products: result }))
        .catch(err => console.log(err));
});

// Route for retrieving a Shop by id and populating it's Product.
// Returns the shop with the product ids, but how to get the product fields???
router.get('/shops/:id', (req, res) => {
    model.Shop.findOne({ _id: req.params.id })
        .populate("product", 'product')
        .then(result => {
            return res.json(result)
        })
        .catch(err => console.log(err));
});

// Route for creating a new Shop
//WORKS
router.post('/add-shop', upload.single('shopImage'), (req, res) => {
    const shop = new model.Shop({
        shopName: req.body.shopName,
        shopCategory: req.body.shopCategory,
        shopDescription: req.body.shopDescription,
        shopImage: req.file
    });
    shop.save()
        .then(result => res.redirect('/shops'))
        .catch(err => console.log(err));
});

// Route for creating a new product and updating Shop "productName" field with it
//WORKS
router.post('/shop/:id', upload.single('productImage'), (req, res) => {
    const id = req.params.id;
    const product = new model.Product({
        product: req.body.product,
        productDescription: req.body.productDescription,
        productPrice: req.body.productPrice,
        inStock: req.body.inStock,
        totalStock: req.body.totalStock,
        productImage: req.file
    })
    product.save()
        .then(productModel => {
        return model.Shop.findOneAndUpdate({ _id: req.params.id }, {$push: {products: productModel._id}}, {new: true})
    })
    .then(result => res.redirect('/products/' + id))
    .catch(err => console.log(err));
});

//get products add page
//WORKS
router.get('/add-product', (req, res) => {
    model.Shop.find()
        .then(result => res.render('shop/add-product', { title: 'Add Product', shops: result, id: result._id }))
        .catch(err => console.log(err));
});

JSON output from one shop. JSON output 来自一家商店。 The products only display IDs.产品仅显示 ID。 Is that right?那正确吗? I am new to this.我是新来的。

{
    "products": [
        "5f01c81db57d61236ddefb95",
        "5f01c878b57d61236ddefb96",
        "5f01cd9735fee92874b446b2",
        "5f01ceddf803982924ecb165"
    ],
    "_id": "5f006113fe371c497fe4d5f6",
    "shopName": "Makro",
    "shopCategory": "Retail",
    "shopDescription": "A massive retail shop",
    "shopImage": {
        "fieldname": "shopImage",
        "originalname": "makro.png",
        "encoding": "7bit",
        "mimetype": "image/png",
        "destination": "public/images/uploads/shop-images",
        "filename": "19ba3c0396f8dfaa63aceaaad24e919f",
        "path": "public/images/uploads/shop-images/19ba3c0396f8dfaa63aceaaad24e919f",
        "size": 97140
    },
    "createdAt": "2020-07-04T10:59:31.705Z",
    "updatedAt": "2020-07-05T13:00:13.802Z",
    "__v": 0
}

I have 2 Schemas.我有 2 个架构。 Shop and Product.商店和产品。 One shop can have many products.一间店铺可以有很多产品。 But I also have more than one Shop.但我也有不止一个商店。 Let's say I have 5 shops, and each of those shops have their own products.假设我有 5 家商店,每家商店都有自己的产品。 I am able to save the products and find their IDs in the Shops respectively.我能够保存产品并分别在商店中找到它们的 ID。 But I am struggling to output products that belong to one specific shop.但我正在努力寻找属于某个特定商店的 output 产品。 I can output each shop by their ID and see all the product IDs added.我可以按每个商店的 ID output 并查看添加的所有产品 ID。 But how do I get the product name, description etc (all Product fields) of each product in a shop?但是如何获取商店中每个产品的产品名称、描述等(所有产品字段)?

My project works like this: I create a shop, then I add products to each shop by selecting the shop's ID and storing the product ID inside the shop.我的项目是这样工作的:我创建一个商店,然后通过选择商店的 ID 并将产品 ID 存储在商店中,将产品添加到每个商店。 Then in my view I want to eventually be able to select a shop and show all the products inside the shop.那么在我看来,我希望最终能够在 select 一个店铺并展示店铺内的所有产品。

I am stuck on getting the rest of the fields for Products.我一直在获取产品字段的 rest。 I have read through the documentation?我已经阅读了文档? Maybe I am missing something.也许我错过了一些东西。 Please help.请帮忙。

My Product model我的产品 model

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    shopName: {
        type: String,
    },
    product: {
        type: String,
        required: true
    },
    productDescription: {
        type: String,
        required: true,
    },
    productPrice: {
        type: Number,
        required: true
    },
    inStock: {
        type: Boolean,
        required: true
    },
    totalStock: {
        type: Number,
        required: true
    },
    productImage: {
        type: Object,
        required: true,
        data: Buffer, 
        contentType: String
    }
});

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

My Shop Model:我的商店 Model:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ShopSchema = new Schema({
    shopName: {
        type: String,
        required: true
    },
    shopImage: {
        type: Object,
        required: true,
        data: Buffer, 
        contentType: String 
    },
    shopDescription: {
        type: String,
        required: true
    },
    shopCategory: {
        type: String,
        required: true
    },
    products: [{
        type: Schema.Types.ObjectId,
        ref: 'productModel'
    }]
}, { timestamps:true });

const Shop = mongoose.model('Shop', ShopSchema);
module.exports = Shop;

My routes:我的路线:

//get all shops
//WORKS
router.get('/shops', (req, res) => {
    model.Shop.find()
        .then(result => res.render('shop/shops', { title: 'Shops', shops: result }))
        .catch(err => console.log(err));
});

//get all products
// HOW TO GET THE PRODUCT NAME, PRICE, DESCR ETC??
router.get('/products/:id', (req, res) => {
    model.Product.find()
        .then(result => res.render('shop/products', { title: 'Products View', products: result }))
        .catch(err => console.log(err));
});

// Route for retrieving a Shop by id and populating it's Product.
// Returns the shop with the product ids, but how to get the product fields???
router.get('/shops/:id', (req, res) => {
    model.Shop.findOne({ _id: req.params.id })
        .populate("product", 'product')
        .then(result => {
            return res.json(result)
        })
        .catch(err => console.log(err));
});

// Route for creating a new Shop
//WORKS
router.post('/add-shop', upload.single('shopImage'), (req, res) => {
    const shop = new model.Shop({
        shopName: req.body.shopName,
        shopCategory: req.body.shopCategory,
        shopDescription: req.body.shopDescription,
        shopImage: req.file
    });
    shop.save()
        .then(result => res.redirect('/shops'))
        .catch(err => console.log(err));
});

// Route for creating a new product and updating Shop "productName" field with it
//WORKS
router.post('/shop/:id', upload.single('productImage'), (req, res) => {
    const id = req.params.id;
    const product = new model.Product({
        product: req.body.product,
        productDescription: req.body.productDescription,
        productPrice: req.body.productPrice,
        inStock: req.body.inStock,
        totalStock: req.body.totalStock,
        productImage: req.file
    })
    product.save()
        .then(productModel => {
        return model.Shop.findOneAndUpdate({ _id: req.params.id }, {$push: {products: productModel._id}}, {new: true})
    })
    .then(result => res.redirect('/products/' + id))
    .catch(err => console.log(err));
});

//get products add page
//WORKS
router.get('/add-product', (req, res) => {
    model.Shop.find()
        .then(result => res.render('shop/add-product', { title: 'Add Product', shops: result, id: result._id }))
        .catch(err => console.log(err));
});

JSON output from one shop. JSON output 来自一家商店。 The products only display IDs.产品仅显示 ID。 Is that right?那正确吗? I am new to this.我是新来的。

{
    "products": [
        "5f01c81db57d61236ddefb95",
        "5f01c878b57d61236ddefb96",
        "5f01cd9735fee92874b446b2",
        "5f01ceddf803982924ecb165"
    ],
    "_id": "5f006113fe371c497fe4d5f6",
    "shopName": "Makro",
    "shopCategory": "Retail",
    "shopDescription": "A massive retail shop",
    "shopImage": {
        "fieldname": "shopImage",
        "originalname": "makro.png",
        "encoding": "7bit",
        "mimetype": "image/png",
        "destination": "public/images/uploads/shop-images",
        "filename": "19ba3c0396f8dfaa63aceaaad24e919f",
        "path": "public/images/uploads/shop-images/19ba3c0396f8dfaa63aceaaad24e919f",
        "size": 97140
    },
    "createdAt": "2020-07-04T10:59:31.705Z",
    "updatedAt": "2020-07-05T13:00:13.802Z",
    "__v": 0
}

pass only product, so it's going to give all details: like this仅传递产品,因此它将提供所有详细信息:像这样

router.get('/shops/:id', (req, res) => {
    model.Shop.findOne({ _id: req.params.id })
        .populate('product')
        .then(result => {
            return res.json(result)
        })
        .catch(err => console.log(err));
});

To get product details everything is in result.要获取产品详细信息,一切都在结果中。 You can use like-你可以使用像 -

result.productPrice...结果.产品价格...

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

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