Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

Mongodb and Express

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}
       }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

}

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

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"
});
}

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!
  });
});

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...