Mongodb和Express [英] Mongodb and Express

查看:49
本文介绍了Mongodb和Express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MongoDB中实现相关的数据概念.我为用户提供了一个集合,为帖子提供了一个集合.现在,帖子集合具有created_by,它表示用户集合.但是,我无法检索相关数据.下面是一些我拥有的架构.

I am trying to implement related data concept in MongoDB. I have one collection for user and one collection for posts. Now posts collection has created_by which refers to users collection. However I am unable to retrieve related data. Below are some of the schema I have.

{   "posts"
        {
            created_by:{ type:mongoose.Schema.ObjectId, ref:'User'},
            created_at:{ type:Date,default:Date.now },
            text:String
        }
}
{
       "users"
         {
             username:String,
             password:String,
             created_at:{type:Date,default:Date.now}
       }
}

推荐答案

http://mongoosejs.com/docs/populate.html 详细说明了一个很好的示例.我为您提取了要点

http://mongoosejs.com/docs/populate.html elaborates with a very nice example. I have extracted the gist here for you

{
var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

}

因此,您现在有了故事和人物两个模型,其中故事通过_creator字段指代人物.

so you now have two models story and person where story refers person via the _creator field.

现在在查询故事时填充_creator,您可以执行以下操作:

now to populate the _creator while querying through story you do the following:

{

Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
  if (err) return handleError(err);
  console.log('The creator is %s', story._creator.name);
  // prints "The creator is Aaron"
});
}

,但是您还需要确保正确保存了记录才能正确检索记录.在保存时,您只需分配_id.见下文.

but you also need to make sure that you have saved the records properly in order to retrieve it properly. while saving you just need to assign the _id. see below.

{
var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });

aaron.save(function (err) {
  if (err) return handleError(err);

  var story1 = new Story({
    title: "Once upon a timex.",
    _creator: aaron._id    // assign the _id from the person
  });

  story1.save(function (err) {
    if (err) return handleError(err);
    // thats it!
  });
});

}

这篇关于Mongodb和Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆