codememo

Mongoose 채우기 하위 하위 문서

tipmemo 2023. 7. 7. 19:04
반응형

Mongoose 채우기 하위 하위 문서

MongoDB에 이 설정이 있습니다.

항목:

title: String
comments: [] // of objectId's

댓글:

user: ObjectId()
item: ObjectId()
comment: String

내 몽구스 스키마는 다음과 같습니다.

itemSchema = mongoose.Schema({
    title: String,
    comments: [{ type: Schema.Types.ObjectId, ref: 'comments' }],
});

Item = mongoose.model('items', itemSchema);

commentSchema = mongoose.Schema({
    comment: String,
    user: { type: Schema.Types.ObjectId, ref: 'users' },
});

Comment = mongoose.model('comments', commentSchema);

여기에서 댓글과 함께 내 아이템을 얻을 수 있습니다.

Item.find({}).populate('comments').exec(function(err, data){
    if (err) return handleError(err);
    res.json(data);
});

댓글 배열을 해당 사용자로 채우려면 어떻게 해야 합니까?각 주석에 사용자 ObjectId()가 있기 때문에?

이를 위한 한 가지 더 쉬운 방법:

Item
  .find({})
  .populate({
	path:     'comments',			
	populate: { path:  'user',
		    model: 'users' }
  })
  .exec(function(err, data){
    if (err) return handleError(err);
    res.json(data);
});

결과 개체에 대한 전체 호출 예제:

Item.find({}).populate("comments").exec(function(err,data) {
    if (err) return handleError(err);

    async.forEach(data,function(item,callback) {
        User.populate(item.comments,{ "path": "user" },function(err,output) {
            if (err) throw err; // or do something

            callback();
        });
    }, function(err) {
        res.json(data);
    });

});

모델에서 호출된 형식의 호출은 문서 또는 배열을 첫 번째 인수로 사용합니다.따라서 각 항목에 대해 반환된 결과를 반복하여 각 "댓글" 배열에서 이 방식으로 호출합니다."경로"는 일치하는 항목을 함수에 알려줍니다.

이 작업은 의 "비차단" 버전을 사용하여 수행되므로 차단되지 않지만, 일반적으로 모든 조작 후 응답의 모든 항목은 주석으로 채워질 뿐만 아니라 주석 자체에도 관련 "사용자" 세부 정보가 있습니다.

더 단순한

Item
  .find({})
  .populate({
    path: 'comments.user',
    model: 'users' }
  })
  .exec(function(err, data){
    if (err) return handleError(err);
    res.json(data);
});

하위 문서에서 특정 필드만 선택하기 위해 사용할 수 있는 마지막 방법을 추가하려면 다음 '선택' 구문을 사용할 수 있습니다.

  Model.findOne({ _id: 'example' })
    .populate({ 
      path: "comments", // 1st level subdoc (get comments)
      populate: { // 2nd level subdoc (get users in comments)
        path: "user",
        select: 'avatar name _id'// space separated (selected fields only)
      }
    })
    .exec((err, res) => { 
        // etc
     });

사용자:

.populate({
            path: 'pathName',
            populate: [
                {
                    path: 'FirstSubPathName',
                    model: 'CorrespondingModel',
                },
                {
                    path: 'OtherSubPathName',
                    model: 'CorrespondingModel',
                },
                {
                    path: 'AnotherSubPathName',
                    model: 'CorrespondingModel',
                },
            ]
        });

내가 이것을 하는 더 쉬운 방법입니다.도움이 될 겁니다.:)

하위 하위 문서를 채우고 여러 스키마에서 채우려면

ProjectMetadata.findOne({id:req.params.prjId})
.populate({
    path:'tasks',
    model:'task_metadata',
    populate:{
        path:'assigned_to',
        model:'users',
        select:'name employee_id -_id' // to select fields and remove _id field

    }
})
.populate({
    path:'client',
    model:'client'
})
.populate({
    path:'prjct_mgr',
    model:'users'
})
.populate({
    path:'acc_exec',
    model:'users'
})
.populate({
    path:'prj_type',
    model:'project_type'
}).then ( // .. your thing

아니면 당신은 다음과 같은 방법으로 그것을 할 수 있습니다.

   ProjectMetadata.findOne({id:req.params.prjId})
    .populate(
        [{
        path:'tasks',
        model:TaskMetadata,
        populate:[{
            path:'assigned_to',
            model:User,
            select:'name employee_id'
        },
        {
            path:'priority',
            model:Priority,
            select:'id title'
        }],
        select:"task_name id code assign_to stage priority_id"
    },
    {
        path:'client',
        model:Client,
        select:"client_name"
    },
    {
        path:'prjct_mgr',
        model:User,
        select:"name"
    },
    {
        path:'acc_exec',
        model:User,
        select:'name employee_id'
    },
    {
        path:'poc',
        model:User,
        select:'name employee_id'
    },
    {
        path:'prj_type',
        model:ProjectType,
        select:"type -_id"
    }

])

같은 상위 하위 하위 문서를 여러 개 가져와야 할 때 두 번째 방법(어레이 사용)이 더 유용하다는 것을 알게 되었습니다.

작업 중인 프로젝트 찾기 및 프로젝트 관련 채우기 작업 및 특정 작업 사용자 찾기

db.Project.find()
.populate({
    path: 'task',
    populate: { path: 'user_id'}
})
.exec(async(error,results)=>{

})

mongoose에서 하위 문서를 채울 수도 있습니다.

Item.find({}).populate("comments.user")

아래 스크린샷을 확인하십시오.이것은 매력적으로 작동합니다!!!enter image description here

이것은 저에게 효과가 있었습니다.

즉, 모델이 필요하지 않음

    .populate({
      path: 'filters',
      populate: {
        path: 'tags',
        populate: {
          path: 'votes.user'
        }
      }
    })
    .populate({
      path: 'members'
    })

언급URL : https://stackoverflow.com/questions/24414975/mongoose-populate-sub-sub-document

반응형