【问题标题】:How to insert into a different collection in node/mongoose application如何在节点/猫鼬应用程序中插入不同的集合
【发布时间】:2021-01-16 15:46:52
【问题描述】:

我是新手,我在 mongodb 中创建了一个数据库,它有两个集合,“用户”和另一个与“用户”分开的集合。

目前,我有一个 nodejs/express 应用程序,它使用 mongoose 在“用户”中输入一个新条目。

如何使用 mongoose 将新条目输入到另一个集合中?可以切换收藏吗?

【问题讨论】:

  • 你应该展示你的一些代码,以便我们更好地理解上下文。

标签: node.js mongodb express mongoose


【解决方案1】:

简单

user.find()......
separateUser.find()...

【讨论】:

    【解决方案2】:

    Mongoose 大大简化了 CRUD 操作。

    您可以创建与数据库中不同集合相对应的特定模式和模型。

    例如:

    const mongoose = require('mongoose')
    
    const userSchema = new mongoose.Schema({
        username: {
            type: String,
            unique: true,
            required: true
        }
    });
    
    const User = mongoose.model('user', userSchema);
    
    const otherSchema = new mongoose.Schema({/* config */});
    
    const Other = mongoose.model('other', otherSchema);
    
    // --- etc...
    
    

    然后你对你创建的模型执行不同的 crud 操作。

    请参阅mongoose docs 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2019-10-26
      • 2020-01-20
      • 2015-06-10
      • 2014-05-09
      • 2016-01-27
      • 2021-11-25
      • 2019-09-06
      • 1970-01-01
      相关资源
      最近更新 更多