一对一与填充猫鼬不起作用

时间:2021-05-28 03:08:14

标签: mongodb mongoose populate

我是 mongoose 和 mongodb 的新手。 我有两个系列(购物车和产品)

1 个购物车有 1 个产品,我拿到了购物车并填充了产品,但没有显示数据关系。 代码如下:

路由

router.route('/relations/:app_id')
.get(cartController.relation);

模型(购物车模型)

var mongoose = require('mongoose');
var cartSchema = mongoose.Schema({
    app_id: {
        type: String,
        required: true
    },
    product_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Produk'
    },
    qty: Number
});

var collectionName = 'cart';
var Cart = module.exports = mongoose.model('Cart', cartSchema, collectionName);

module.exports.get = function (callback, limit) {
    Cart.find(callback).limit(limit);
}

模型(produkModel)

var mongoose = require('mongoose');

// Setup schema
var produkSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    stok: Number
});

// Export Cart model
var collectionName = 'produk';
var Produk = module.exports = mongoose.model('Produk', produkSchema, collectionName);

module.exports.get = function (callback, limit) {
    Produk.find(callback).limit(limit);
}

控制器(cartController)

Cart = require('../model/cartModel');
exports.relation = function (req, res) {
const showCart = async function() {
    const carto = await Cart.find().select('app_id product_id qty').populate("produk");

    return carto;
};

showCart()
  .then(cs => {
    return apiResponse.successResponseWithData(res, "Operation success", cs);
  })
  .catch(err => console.log(err));

};

// 结果

{
"status": 1,
"message": "Operation success",
"data": [
    {
        "_id": "60af72022d57d542a41ffa5a",
        "app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
        "qty": 1,
        "product_id": "60112f3a25e6ba2369424ea3"
    },
    {
        "_id": "60b020536ccea245b410fb38",
        "app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
        "product_id": "603f5aff9437e12fe71e6d41",
        "qty": 1
    }
]
}

期待结果

{
"status": 1,
"message": "Operation success",
"data": [
    {
        "_id": "60af72022d57d542a41ffa5a",
        "app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
        "qty": 1,
        "product_id": {
             "_id": "60112f3a25e6ba2369424ea3",
             "name": "snack"
         }
    },
    {
        "_id": "60b020536ccea245b410fb38",
        "app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
        "product_id": {
             "_id": "603f5aff9437e12fe71e6d41",
             "name": "snack"
         }
        "qty": 1
    }
]
}

我想念什么???

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您需要将要填充的路径或指定参数的对象传递给 .populate()。所以在这种情况下,你的代码应该是:

const carto = await Cart.find().select('app_id product_id qty').populate("product_id");