当前位置: 首页 > 知识库问答 >
问题:

err:=db.model(&users).where(“id in(?)”,pg.in(ids)).select()在mongodb中的等价物是什么

胡曾笑
2023-03-14

我正在尝试将一个go backend项目从postgres切换到mongodb,最后一个我无法修复的缺失部分是

err := db.Model(&users).Where("id in (?)", pg.In(ids)).Select()

有谁能帮我在mongodb中找到它的等价物吗

这是我要更改的代码


const userloaderKey = "userloader"

func DataloaderMiddleware(db *pg.DB, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        userloader := UserLoader{
            maxBatch: 100,
            wait:     1 * time.Millisecond,
            fetch: func(ids []string) ([]*models.User, []error) {
                var users []*models.User

                err := db.Model(&users).Where("id in (?)", pg.In(ids)).Select()

                if err != nil {
                    return nil, []error{err}
                }

                u := make(map[string]*models.User, len(users))

                for _, user := range users {
                    u[user.ID] = user
                }

                result := make([]*models.User, len(ids))

                for i, id := range ids {
                    result[i] = u[id]
                }

                return result, nil
            },
        }

        ctx := context.WithValue(r.Context(), userloaderKey, &userloader)

        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func getUserLoader(ctx context.Context) *UserLoader {
    return ctx.Value(userloaderKey).(*UserLoader)
}


共有1个答案

壤驷棋
2023-03-14

等价物如下所示

ids := []primitive.ObjectID{ // contains some IDs }
users := client.Database("myDatabase").Collection("users")

cur, err := users.Find(context.TODO(), bson.M{"_id": bson.M{"$in": ids}})
 类似资料: