【问题标题】:Use mongoose schema and save to different collections使用猫鼬模式并保存到不同的集合
【发布时间】:2020-03-27 05:10:39
【问题描述】:

我的目标是学习如何使用模型来保存所需的集合(集合名称 = 年份),我创建的要解决的问题如下:假设我正在处理剩余的学校/大学课程的数据相同(名称、位置等),但唯一的变量是 2019 年、2020 年等。

我知道我只能使用一个集合并按某个 idyear 过滤,但我认为将其分成一个按年份命名的新集合可能会更好,这样我就可以得到类似的东西:

  • 2018 年系列 -> X 项
  • 2019 年系列 -> Y 项
  • 2020 年系列 -> Z 项

我尝试了以下代码:

classModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const classSchema = new Schema({
    name: {type: String, required: true},
    info1: {type: String},
    iduser: {type: Number}
});

module.exports = mongoose.model('Classes', classSchema);

classController.js

const classModel = require('classModel');
const userModel = require('userModel');
exports.insertClass = async function(req, res){

    const user = await userModel.find({
        username: req.user
    }).limit(1);

    await classModel.create({
        name: req.name,
        info1: req.location,
        iduser: user[0].idperson
    }, {collection: '999999'}, function(err){
        if(err) console.log(err);
        res.sendStatus(200);
    });

}

我现在正在硬编码的那一年,但我计划附加到用户会话(因此我使用另一个搜索)。 使用此代码,我可以设法根据模型名称在集合中插入模型的默认行为,但这不是我的目标,最终会得到类似的结果:

  • 集合类 -> X+Y+Z

我正在阅读 mongoose 文档并找到了“选项”和“设置”,因此我尝试将集合名称强制放入其中(如 this question)但无法做到。

我在周末遇到了这个问题,所以我不能说我是在某个时候“俯瞰”还是刚刚进入节点,如果有人能指出我的方向,我会很高兴,我希望问题很明确。

【问题讨论】:

  • 我认为你是在为你发明问题,只使用一个集合。

标签: node.js mongodb mongoose schema


【解决方案1】:

您将无法使用单个架构动态更改类集合。您需要为每个集合创建多个类模式,即

const class2018 = new Schema(
const class2019 = new Schema(
const class20220 = new Schema(

然后找出客户端使用的架构。

这种方法没有任何好处,当您尝试加入和查询这些关系时,您只是在制造复杂性和进一步的挑战。

我会在你将加入的字段上创建一个单一的类集合,如year 并完成。易于管理,易于加入,这是 mongoose 期望的设计,当您开始进行聚合查询时,您将不会那么头疼。

【讨论】:

  • 通过新的 $unionWith 聚合阶段将相同的模型数据拆分为多个集合,这对于大型数据集具有很强的用例。
猜你喜欢
  • 2016-01-27
  • 2018-08-27
  • 2016-05-01
  • 2014-12-21
  • 2016-11-18
  • 2020-09-05
  • 2016-05-28
  • 1970-01-01
  • 2017-06-12
相关资源
最近更新 更多