首页 > 解决方案 > 在 MongoDB 中链接不相关的集合

问题描述

我有一个显示艺术家和场地记录的应用程序在他们的用户个人资料页面上创建了我的特定用户,并且还在这些记录下显示用户评论(和用户名)。此代码工作正常。

但是,在 Artist 记录下,我还想显示所有的 VENUES,以便艺术家可以选择(即标记)他们在哪些场所演奏过。同样,场地可以标记哪些艺术家在场地演奏过。

与当前用户模型的不同之处在于,用户直接链接到艺术家/场地记录,因为他们创建了它们。另一方面,艺术家和场地目前根本没有联系,所以我正在为如何将它们联系在一起而苦苦挣扎。我怀疑这个问题与我在 Artist Mongoose 模式中定义场所的方式有关,但我对此仍然很陌生,因此寻求一些指导。我收到的错误消息是“地点未定义”。

艺术家架构:

 // SCHEMA SETUP - Artist
    var artistSchema = new mongoose.Schema({
       name: String,
       logo: String,
       shortDescription: String,
       createdAt:{
            type:Date,
            default:Date.now
       },
       author: {
          id: {
             type: mongoose.Schema.Types.ObjectId,
             ref: "User" //references user model
          },
          username: String
       },
       comments: [
          {
             type: mongoose.Schema.Types.ObjectId,
             ref: "Comment"
          }   
       ],
       venue: {
           id: {
             type: mongoose.Schema.Types.ObjectId,
             ref: "Venue"     
           },
           name: String 
       }

    });

    var Artist = mongoose.model("Artist", artistSchema);

场地示意图:

// SCHEMA SETUP - Venue
var venueSchema = new mongoose.Schema({
   name: String,
   logo: String,
   address: String,
   contact: String,
   createdAt:{
        type:Date,
        default:Date.now
   },
   author: {
      id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User" //references user model
      },
      username: String
   }
});

秀艺路线:

// SHOW - shows more info about one artist
app.get("/artist/:id", function(req, res){
    //find the artist with provided ID
    Artist.findById(req.params.id).populate("comments").exec(function(err, foundArtist){
        Venue.find().exec(function (err, venues) {
            if(err){
                console.log(err);
            } else {
                //render show template with that artist
                res.render("show", {artist: foundArtist});
            }
        });
    });
})

在艺术家页面(show.ejs)上显示场地的代码:

    <div class="row">
        <div class="col-md-4">
            <% venues.forEach(function(venue) { %>
                <li><a href="/venue/<%=artist.venue.id %>"><%= artist.venue.name %></a></li>
            <% }); %>
        </div>
    </div>

提前致谢!

标签: mongodbmongoose

解决方案


推荐阅读