【发布时间】:2020-08-24 22:36:32
【问题描述】:
试图通过动态传递集合名称从表中获取数据但不起作用。我有两个表 [shoptable 和 markettable] 和相同的标题数据。我想获取数据取决于传递集合名称。我不知道如何设置动态集合的架构。任何人都可以找到我在哪里做错了吗?
table.controller.js //Nodejs
const mongoose = require('mongoose');
const _ = require('lodash');
var Schema = mongoose.Schema;
let dynamicModels = {};
const ConvForUserSchema = new Schema({
product_name: {
type: String
},
price: {
type: String
},
catogery: {
type: String
}
}, {
versionKey: false,
strict: false
});
const dynamicModel = (collectionName) => {
if (!(collectionName in dynamicModels)) {
dynamicModels[collectionName] = mongoose.model(collectionName, ConvForUserSchema, collectionName);
}
return dynamicModels[collectionName];
};
module.exports.getTableData = (req, res, next) => {
let collection = req.query.collection;
console.log("col=" + collection)
dynamicModel(collection).find({}, function(err, docs) {
if (err) {
console.log('ss' + err);
return
}
return res.json(docs);
})
}
user.service.ts:
getTableData(collection){
return this.http.get(`http://localhost:3000/api/getTableData?collection=${collection}`);
}
product.component.js:
shopDatas(){
this.getProductsData('shoptable');
}
marketDatas(){
this.getProductsData('markettable');
}
getProductsData(collection){
this.userService.getTableData(collection).subscribe(
res => {
this.tableData = res;
},
err => {
console.log(err);
}
);
}
product.component.html:
<button (click)="shopDatas()">Shop data</button>
<button (click)="marketDatas()">Market data</button>
【问题讨论】:
-
为两个集合创建两个单独的猫鼬模式,并要求控制器中的猫鼬模型和根据条件选择模型。
-
@Aabid:你能更新我的代码吗?
标签: node.js mongoose angular8 mongoose-schema