简体   繁体   English

MongoDB对象类型/嵌套模式

[英]MongoDB object type/nested schema

Okay so I have an events.js file with an eventSchema: 好的,所以我有一个带有eventSchema的events.js文件:

var eventSchema = mongoose.Schema({
name:{
    type: String,
    //required: true
venue:{

}
});

and a venue.js with the venue schema: 以及一个带有会场架构的会场.js:

var mongoose = require('mongoose'); var mongoose = require('mongoose');

var venueSchema = mongoose.Schema(
{
name:{
    type: String,
    //required: true
},
postcode:{
    type: String,
    //required: true
},
town:{
    type: String,
    //required: true
}
});

My question is how can I have the 'venue' field in the events schema be linked to the venue schema. 我的问题是如何将事件模式中的“场地”字段链接到场地模式。 So essentially when you create a new event you can only add a venue from the list of venues. 因此,基本上,当您创建一个新事件时,您只能从场所列表中添加一个场所。 Thanks in advance! 提前致谢!

You can link it by id. 您可以按ID链接。 You don't have to add all 'venue' field in the events schema. 您无需在事件架构中添加所有“地点”字段。

var eventSchema = mongoose.Schema({
  name:{
    type: String,
    //required: true
  },
  venue_id: Schema.Types.ObjectId,
});

Since you're using Mongoose, You can make field like, 由于您使用的是猫鼬,因此您可以将字段设置为

venue_id: { type: Schema.Types.ObjectId, ref: 'Venue' }

which uses populate method. 使用填充方法。

Population is the process of automatically replacing the specified paths (which is venue_id) in the document with document(s) from other collection(s) (which is document matched with venue_id). 填充是将文档中的指定路径 (即场所ID)自动替换为其他集合(与场所ID匹配的文档中的文档的过程。

You can use it like 你可以像这样使用它

event.
  findOne({ name: 'somename' }).
  populate('venue').
  exec(function (err, event) {
    if (err) return handleError(err);
});

It will return event doc with venue doc that match with venue_id, not just venue_id. 它将返回事件文档,其事件文档与不但会场ID匹配,而且会场ID匹配。

The answer given by @godsnam is correct but when you want to use references in your schema. @godsnam给出的答案是正确的,但是当您要在架构中使用引用时。 If you don't want to do it using references then this might help you. 如果您不想使用引用来做,那么这可能会对您有所帮助。

You can do link your venueSchema in eventSchema by simply writing as below. 您可以通过简单地编写如下内容,将eventSchema链接到eventSchema中。

var venueSchema = mongoose.Schema(
    {
        name: {
            type: String,
            //required: true
        },
        postcode: {
            type: String,
            //required: true
        },
        town: {
            type: String,
            //required: true
        }
    });

var eventSchema = mongoose.Schema({
    name: {
        type: String,
        //required: true
    },
    venue: venueSchema
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM