如何检索以猫鼬一对多关系存储的文档

时间:2020-07-05 14:40:20

标签: javascript node.js mongodb express mongoose

我有2个架构。商店和产品。一个商店可以有很多产品。但我也有多家商店。假设我有5家商店,每个商店都有自己的产品。我能够保存产品并分别在商店中找到其ID。但是我正在努力输出属于一个特定商店的产品。我可以按他们的ID输出每个商店,并查看添加的所有产品ID。但是,如何获得商店中每种产品的产品名称,描述等(所有产品字段)?

我的项目是这样的:创建一个商店,然后通过选择商店的ID并将产品ID存储在商店中来向每个商店添加产品。然后在我看来,我希望最终能够选择一家商店并展示商店内的所有产品。

我坚持获取其余产品字段!我已经阅读了文档。也许我缺少什么?请帮忙。

我的产品型号

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;

我的商店型号:

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;

我的路线:

//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输出。产品仅显示ID。是对的吗?我是新来的。

{
    "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
}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

仅通过产品,因此它将提供所有详细信息:像这样

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

要获取产品详细信息,请执行所有操作。您可以使用like-

result.productPrice ...