복붙노트

[MONGODB] ID가 아닌 필드와 몽구스 모델을 채 웁니다

MONGODB

ID가 아닌 필드와 몽구스 모델을 채 웁니다

그것이 가능하면 _id가 아닌 참조 모델의 필드 ... 예와 몽구스 모델을 채 웁니다 사용자 이름.

같은 뭔가

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : { type: String, field: "username", ref: 'Story' }
});

해결법

  1. ==============================

    1.당신은 채우기 () API를 사용할 수 있습니다. 이 API가 더 유연, 당신은 스키마에서 심판과 필드를 지정할 필요가 없습니다.

    당신은 채우기 () API를 사용할 수 있습니다. 이 API가 더 유연, 당신은 스키마에서 심판과 필드를 지정할 필요가 없습니다.

    http://mongoosejs.com/docs/api.html#document_Document-populate http://mongoosejs.com/docs/api.html#model_Model.populate

    당신은 혼합 발견과 일치시킬 수 있습니다 ().

  2. ==============================

    2.이 몽구스 4.5부터 지원되며,에서 가상 인구라고합니다.

    이 몽구스 4.5부터 지원되며,에서 가상 인구라고합니다.

    당신은 당신의 스키마 정의 후이 같은 모델을 만들기 전에 외래 키 관계를 정의해야합니다 :

    // Schema definitions
    
    BookSchema = new mongoose.Schema({
            ...,
            title: String,
            authorId: Number,
            ...
        },
        // schema options: Don't forget this option
        // if you declare foreign keys for this schema afterwards.
        {
            toObject: {virtuals:true},
            // use if your results might be retrieved as JSON
            // see http://stackoverflow.com/q/13133911/488666
            //toJSON: {virtuals:true} 
        });
    
    PersonSchema = new mongoose.Schema({id: Number, ...});
    
    
    // Foreign keys definitions
    
    BookSchema.virtual('author', {
      ref: 'Person',
      localField: 'authorId',
      foreignField: 'id',
      justOne: true // for many-to-1 relationships
    });
    
    
    // Models creation
    
    var Book = mongoose.model('Book', BookSchema);
    var Person = mongoose.model('Person', PersonSchema);
    
    
    // Querying
    
    Book.find({...})
        // if you use select() be sure to include the foreign key field !
        .select({.... authorId ....}) 
        // use the 'virtual population' name
        .populate('author')
        .exec(function(err, books) {...})
    
  3. ==============================

    3.그것은 그들이 _id 사용하도록 강제하고, 어쩌면 우리가 미래에 그것을 사용자 정의 할 수 있습니다 보인다.

    그것은 그들이 _id 사용하도록 강제하고, 어쩌면 우리가 미래에 그것을 사용자 정의 할 수 있습니다 보인다.

    여기 Github에서의 문제가 https://github.com/LearnBoost/mongoose/issues/2562

  4. ==============================

    4.이 사용하는 예제입니다 $ 조회 집계 해당 이메일 필드를 기준으로 각각의 사용자로 초대라는 모델을 채우려면 :

    이 사용하는 예제입니다 $ 조회 집계 해당 이메일 필드를 기준으로 각각의 사용자로 초대라는 모델을 채우려면 :

      Invite.aggregate(
          { $match: {interview: req.params.interview}},
          { $lookup: {from: 'users', localField: 'email', foreignField: 'email', as: 'user'} }
        ).exec( function (err, invites) {
          if (err) {
            next(err);
          }
    
          res.json(invites);
        }
      );
    

    아마 당신이 뭘하려는 건지 매우 유사합니다.

  5. from https://stackoverflow.com/questions/19287142/populate-a-mongoose-model-with-a-field-that-isnt-an-id by cc-by-sa and MIT license