【问题标题】:How to retrieve documents stored in one to many relationship in Mongoose如何在猫鼬中检索以一对多关系存储的文档
【发布时间】:2020-10-25 18:06:39
【问题描述】:

我有 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
}

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    只通过产品,所以它会给出所有细节:像这样

    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 ...

    【讨论】:

    • 那是我不明白的。当我将 result.productPrice 记录到控制台时,我得到了 undefined。
    • 在控制台打印结果,看看数据是怎么来的。
    • 这就是我记录它的地方,就在返回res.json(result) 行之前,我正在记录它。我得到undefined。当我只记录console.log(result) 时,我得到了我的问题中的 json 数据。我只能返回产品的 ID,不能返回产品架构的其他字段。
    • 在商店里试试这个 populate("_id.products")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2018-08-23
    • 2020-07-02
    • 1970-01-01
    • 2015-07-12
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多