Mongo - 如何在保存数据时将集合名称传递给 Schema

Mongo - How can I pass collection name to Schema while saving data

我对这里的猫鼬无能为力,但不确定我哪里出错了。请帮帮我。

假设我定义我的模式如下:

const userDBSchema = new Schema({
    userName: {
        type:String
    },
    musicType: {
        type: String,
    },
}, { collection: 'userData' });

然后运行一个post到数据库,使用这个函数:

exports.saveUser = (req, res) => {
    const username = req.params.user;

    const newUser = new UserInfoDb(req.body, {'collection': username});
    newUser.save((err, response) => {
      //save operation
    });
};

我收到这个错误:

{
    "message": "document must have an _id before saving",
    "name": "MongooseError"
}

即使我手动定义 id,我的架构中也包含以下内容:

    _id: {
        type: mongoose.Schema.Types.ObjectId,
        index: true,
        required: true,
        auto: true
    },

我收到这个错误:

{
    "errors": {
        "_id": {
            "message": "Path `_id` is required.",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `_id` is required.",
                "type": "required",
                "path": "_id"
            },
            "kind": "required",
            "path": "_id"
        }
    },
    "_message": "userDB validation failed",
    "message": "userDB validation failed: _id: Path `_id` is required.",
    "name": "ValidationError"
}

最终我的目标是我可以传入我想从 POST 访问的集合的名称,然后将我的请求正文写入该集合。我有多个集合,我可能需要在任何给定时间写信给它们。我权衡了将所有内容都放在一个集合中的决定,但决定使用多个集合来存储我的数据。

您能否确认您想要多个 collection,每个用户都有自己的数据库 collection?我认为这不是一个好的决定!

这是我的解决方案。您可以使用相同的模式(userDBSchema 您创建的)为每个用户创建一个模型。

但是您应该确保可以为每个用户生成唯一的 collection 名称。 (例如哈希函数或其他任何东西)

我想再次确认,这不是为每个用户创建 collection 来存储他的信息的好方法。

为什么?

如果您的系统有数百万用户,您将有数百万 collections,管理数据库非常复杂。最好在 collection 中包含数百万个文档。这是我个人的想法。希望能帮到你

const mongoose = require('mongoose');
const userDBSchema = require('path/to/your/schema/declared');

// Generating unique collection name for each user
const getCollectionNameForUser = (username) => username;

exports.saveUser = (req, res) => {
    const username = req.params.user;

    const UserInfoDb = mongoose.model(getCollectionNameForUser(username), userDBSchema);

    const newUser = new UserInfoDb(req.body);
    newUser.save((err, response) => {
      //save operation
    });
};

编辑 - 简单演示

这是我的演示简单应用程序,如何使用 mongoose 中的模式创建动态模型,您可以在此处查看完整代码并在本地数据库上试用 https://gist.github.com/huynhsamha/4dcf00a1fba96ae7f186b606b33b7e9c

在我的演示中,我创建了一个存储用户信息的模式

const Schema = mongoose.Schema;

const UserInfoSchema = new Schema({
  note: String,
  timeline: { type: Date, default: Date.now }
});

并通过简单的 API GET

向每个用户添加 log(使用 note
app.get('/add/:id/:note', async (req, res) => {
  const { id, note } = req.params;
  // Retrieve model which contain info documents of user with id
  const UserInfo = mongoose.model('User_' + id, UserInfoSchema);

  const log = new UserInfo({ note });
  await log.save();
  res.send(log);
})

这是API检索用户日志

app.get('/:id', async (req, res) => {
  const { id } = req.params;
  // Retrieve model which contain info documents of user with id
  const UserInfo = mongoose.model('User_' + id, UserInfoSchema);

  const logs = await UserInfo.find();
  res.send(logs);
})

我已经测试了这段代码,它可以正常工作。每个用户都有一个collection来存储他的数据信息。

您可以使用 gist https://gist.github.com/huynhsamha/4dcf00a1fba96ae7f186b606b33b7e9c 中的代码在本地下载并检查它。