【问题标题】:How to get data by dynamic collection name in nodejs and mongoose如何通过nodejs和mongoose中的动态集合名称获取数据
【发布时间】: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


【解决方案1】:
const newCollection = mongoose.model("collectionName" , Schema)
  newCollection.find({} , (err, docs)=>{
    console.log(docs)
  })

【讨论】:

  • 您好,欢迎来到 SO。请阅读here,它将帮助您更顺利地开始。 :)
猜你喜欢
  • 2013-07-22
  • 2014-09-22
  • 2020-08-06
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2020-08-24
  • 2015-05-21
  • 2019-08-22
相关资源
最近更新 更多