【问题标题】:Referencing another schema in Mongoose在 Mongoose 中引用另一个模式
【发布时间】:2013-08-02 19:32:26
【问题描述】:

如果我有两个模式,例如:

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var  User = mongoose.model('User') 

var postSchema = new Schema({
    name: String,
    postedBy: User,  //User Model Type
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

我尝试像上面的示例一样将它们连接在一起,但我不知道该怎么做。最终,如果我能做这样的事情,那我的生活会很轻松

var profilePic = Post.postedBy.profilePic

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    听起来 populate 方法正是您想要的。首先对您的帖子架构进行一些小改动:

    var postSchema = new Schema({
        name: String,
        postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
        dateCreated: Date,
        comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
    });
    

    然后制作你的模型:

    var Post = mongoose.model('Post', postSchema);
    

    然后,当您进行查询时,您可以像这样填充引用:

    Post.findOne({_id: 123})
    .populate('postedBy')
    .exec(function(err, post) {
        // do stuff with post
    });
    

    【讨论】:

    • “ref”字段有什么用?我找不到关于它的文档。
    • @KarlMorrison ref 字段表示将在哪个集合中搜索提到的 id。
    • populate 和 addToSet 有什么区别?
    • by:selectro 的参考文献在哪里
    • @KarlMorrison “ref”的文档隐藏在populate:mongoosejs.com/docs/populate.html的文档中
    【解决方案2】:

    附录:没有人提到“填充” --- 非常值得您花时间和金钱查看 Mongooses 填充方法:还解释了跨文档引用

    http://mongoosejs.com/docs/populate.html

    【讨论】:

      【解决方案3】:

      回复晚了,不过补充一下Mongoose也有Subdocuments的概念

      使用此语法,您应该能够将您的 userSchema 引用为您的 postSchema 中的一个类型,如下所示:

      var userSchema = new Schema({
          twittername: String,
          twitterID: Number,
          displayName: String,
          profilePic: String,
      });
      
      var postSchema = new Schema({
          name: String,
          postedBy: userSchema,
          dateCreated: Date,
          comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
      });
      

      注意更新后的 postedBy 字段类型为 userSchema

      这会将用户对象嵌入帖子中,从而节省使用引用所需的额外查找。有时这可能更可取,其他时候 ref/populate 路线可能是要走的路。取决于您的应用程序在做什么。

      【讨论】:

        【解决方案4】:
        {body: "string", by: mongoose.Schema.Types.ObjectId}
        

        mongoose.Schema.Types.ObjectId 将创建一个新的 id,尝试将其更改为更直接的类型,如字符串或数字。

        【讨论】:

          【解决方案5】:

          这是对 D. Lowe 的回答的补充,它对我有用,但需要一些调整。 (我会将此作为评论,但我没有这样做的声誉,我希望在几个月后再次遇到此问题时看到此信息,但我忘记了如何解决它。)

          如果您要从另一个文件导入 Schema,则需要在导入的末尾添加 .schema。

          注意:如果您不导入架构并改用本地架构,但导入对我来说更简洁且更易于处理,我不确定您是否获得了无效的架构配置。

          例如:

          // ./models/other.js
          const mongoose = require('mongoose')
          
          const otherSchema = new mongoose.Schema({
              content:String,
          })
          
          module.exports = mongoose.model('Other', otherSchema)
          
          //*******************SEPERATE FILES*************************//
          
          // ./models/master.js
          const mongoose = require('mongoose')
          
          //You will get the error "Invalid schema configuration: `model` is not a valid type" if you omit .schema at the end of the import
          const Other=require('./other').schema
          
          
          const masterSchema = new mongoose.Schema({
              others:[Other],
              singleOther:Other,
              otherInObjectArray:[{
                  count:Number,
                  other:Other,
              }],
          })
          
          module.exports = mongoose.model('Master', masterSchema);
          

          然后,无论你在哪里使用它(对我来说,我在我的 Node.js API 中使用了类似的代码),你可以简单地将 other 分配给 master。

          例如:

          const Master= require('../models/master')
          const Other=require('../models/other')
          
          router.get('/generate-new-master', async (req, res)=>{
              //load all others
              const others=await Other.find()
          
              //generate a new master from your others
              const master=new Master({
                  others,
                  singleOther:others[0],
                  otherInObjectArray:[
                      {
                          count:1,
                          other:others[1],
                      },
                      {
                          count:5,
                          other:others[5],            
                      },
                  ],
              })
          
              await master.save()
              res.json(master)
          })
          

          【讨论】:

            猜你喜欢
            • 2022-01-21
            • 2015-05-18
            • 1970-01-01
            • 2021-07-31
            • 2015-12-13
            • 2020-09-26
            • 1970-01-01
            • 2016-03-18
            • 1970-01-01
            相关资源
            最近更新 更多