mongodb - 一对一填充猫鼬不工作
问题描述
我是 mongoose 和 mongodb 的新手。我有两个系列(购物车和产品)
1 个购物车有 1 个产品,我得到了购物车并填充了产品,但没有显示数据关系。这里的代码:
路由
router.route('/relations/:app_id')
.get(cartController.relation);
型号 (cartModel)
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);
}
控制器(购物车控制器)
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
}
]
}
我想念什么???
谢谢你的帮助
解决方案
您需要将要填充的路径或指定参数的对象传递给.populate()。所以在这种情况下,你的代码应该是:
const carto = await Cart.find().select('app_id product_id qty').populate("product_id");
推荐阅读
- google-apps-script - #参考!通过 setFormula() 而不是实际参考添加到公式中: IF(NOT(ISBLANK(N3)),#REF!,0))
- vue.js - vue.js 代码中用于自动完成的语法错误
- ios - 拖放Containerview没有出现
- java - 正则表达式模式 - 查询
- node.js - sage 8.5.1 中的 gulp watch 问题
- mongodb - kubernetes 更新后,kubernetes 上的 mongodb StatefulSet 不再工作
- python - 将项目添加到类实例中的列表中
- java - 连接器 J 安装
- r - R 和指数,标准二阶
- reactjs - [Webpack][React] 在带有代码拆分的 SSR 上,我如何获取页面所需的块列表?