programing

2D Geo Index를 사용하여 Mongoose 스키마의 배열에서 개체를 올바르게 정의하는 방법

linuxpc 2023. 4. 6. 21:10
반응형

2D Geo Index를 사용하여 Mongoose 스키마의 배열에서 개체를 올바르게 정의하는 방법

현재 아래 문서의 스키마를 만드는 데 문제가 있습니다.서버의 응답은 항상 "trk" 필드 값을 [Object]로 반환합니다.저는 적어도 이치에 맞는 모든 방법을 시도해 보았기 때문에 어떻게 해야 할지 모르겠습니다;-)

이것이 도움이 된다면, 나의 Mongoose 버전은 3.6.20이고 MongoDB 2.4.7입니다. 그리고 잊어버리기 전에 Index (2d)로도 설정하면 좋을 것 같습니다.

원본 데이터:

{
    "_id": ObjectId("51ec4ac3eb7f7c701b000000"),
    "gpx": {
        "metadata": {
            "desc": "Nürburgring VLN-Variante",
            "country": "de",
            "isActive": true
        },
    "trk": [
    {
        "lat": 50.3299594,
        "lng": 6.9393006
    },
    {
        "lat": 50.3295046,
        "lng": 6.9390688
    },
    {
        "lat": 50.3293714,
        "lng": 6.9389939
    },
    {
        "lat": 50.3293284,
        "lng": 6.9389634
    }]
    }
}

Mongoose 스키마:

var TrackSchema = Schema({
            _id: Schema.ObjectId,
            gpx: {
                metadata: {
                    desc: String,
                    country: String,
                    isActive: Boolean
                },
                trk: [{lat:Number, lng:Number}]
            }
        }, { collection: "tracks" });

Chrome의 [Network]탭의 응답은 항상 다음과 같습니다(잘못된 것은 trk 부분뿐입니다).

{ trk: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],

이미 "trk"에 대해 다른 스키마 정의를 시도했습니다.

  1. trk: 스키마.Types.혼합
  2. trk: [스케마]Types.Mixed]
  3. trk:[ { type : ][숫자], 인덱스: "2d" }]

잘 부탁드립니다;-)

trk는 다음 방법으로 선언할 수 있습니다. - 다음 중 하나

trk : [{
    lat : String,
    lng : String
     }]

또는

trk : { type : Array , "default" : [] }

두 번째 경우 삽입 중 객체를 만들고 다음과 같이 어레이에 밀어넣습니다.

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

또는 오브젝트의 배열을 다음과 같이 설정할 수 있습니다.

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

저도 mongoose에 대해 비슷한 문제가 있었습니다.

fields: 
    [ '[object Object]',
     '[object Object]',
     '[object Object]',
     '[object Object]' ] }

실제로 스키마에서 속성 이름으로 "type"을 사용하고 있었습니다.

fields: [
    {
      name: String,
      type: {
        type: String
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

이 동작을 방지하려면 파라미터를 다음과 같이 변경해야 합니다.

fields: [
    {
      name: String,
      type: {
        type: { type: String }
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

스키마에서 배열을 작성하려면 다음과 같이 스키마를 하나 더 만들어야 합니다.monetizationSchema한 번에 하나의 데이터를 저장하고 다른 데이터를 저장하기 위해 사용됩니다.blogSchema우리는 가지고 있다.monetization포함하는 필드monetizationSchema대괄호로 묶어서 배열합니다.

Schema한 번에 하나의 데이터를 저장할 수 있습니다.

const monetizationSchema = new Schema({
      amazonUrl: {
        type: String,
        required: true,
      } 
    });

스키마monetization배열로서

const blogSchema = {
  monetization: [
   monetizationSchema
  ],
  image: {
   type: String,
   required: true
  },
  // ... etc
});

다음과 같이 어레이를 선언할 수 있습니다.

trk : [{
    lat : String,
    lng : String
}]

하지만 그것은 정해질 것이다.[](빈 배열)을 기본값으로 사용합니다.

이 기본값을 덮어쓰지 않으려면 기본값을 다음과 같이 설정해야 합니다.undefined아래와 같이

trk: {
    type: [{
        lat : String,
        lng : String
    }],
    default: undefined
}

해결해야 할 문제는 몇 개의 필드(주소, 도서, num_of_days, biller_addr, blk_data)를 포함하는 계약서를 저장하는 것입니다.blk_data는 거래 목록(블록 번호와 거래 주소)입니다.이 문답은 나에게 도움이 되었다.제 코드를 아래와 같이 공유하고 싶습니다.이게 도움이 됐으면 좋겠다.

  1. 스키마 정의blk_data를 참조하십시오.
var ContractSchema = new Schema(
    {
        address: {type: String, required: true, max: 100},  //contract address
        // book_id: {type: String, required: true, max: 100},  //book id in the book collection
        book: { type: Schema.ObjectId, ref: 'clc_books', required: true }, // Reference to the associated book.
        num_of_days: {type: Number, required: true, min: 1},
        borrower_addr: {type: String, required: true, max: 100},
        // status: {type: String, enum: ['available', 'Created', 'Locked', 'Inactive'], default:'Created'},

        blk_data: [{
            tx_addr: {type: String, max: 100}, // to do: change to a list
            block_number: {type: String, max: 100}, // to do: change to a list
        }]
    }
);
  1. MongoDB에 컬렉션 레코드를 만듭니다.blk_data를 참조하십시오.
// Post submit a smart contract proposal to borrowing a specific book.
exports.ctr_contract_propose_post = [

    // Validate fields
    body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
    body('req_addr', 'req_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('new_contract_addr', 'contract_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
    body('num_of_days', 'num_of_days must not be empty.').isLength({ min: 1 }).trim(),

    // Sanitize fields.
    sanitizeBody('*').escape(),
    // Process request after validation and sanitization.
    (req, res, next) => {

        // Extract the validation errors from a request.
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            // There are errors. Render form again with sanitized values/error messages.
            res.status(400).send({ errors: errors.array() });
            return;
        }

        // Create a Book object with escaped/trimmed data and old id.
        var book_fields =
            {
                _id: req.body.book_id, // This is required, or a new ID will be assigned!
                cur_contract: req.body.new_contract_addr,
                status: 'await_approval'
            };

        async.parallel({
            //call the function get book model
            books: function(callback) {
                Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
            },
        }, function(error, results) {
            if (error) {
                res.status(400).send({ errors: errors.array() });
                return;
            }

            if (results.books.isNew) {
                // res.render('pg_error', {
                //     title: 'Proposing a smart contract to borrow the book',
                //     c: errors.array()
                // });
                res.status(400).send({ errors: errors.array() });
                return;
            }

            var contract = new Contract(
                {
                    address: req.body.new_contract_addr,
                    book: req.body.book_id,
                    num_of_days: req.body.num_of_days,
                    borrower_addr: req.body.req_addr

                });

            var blk_data = {
                    tx_addr: req.body.tx_addr,
                    block_number: req.body.block_number
                };
            contract.blk_data.push(blk_data);

            // Data from form is valid. Save book.
            contract.save(function (err) {
                if (err) { return next(err); }
                // Successful - redirect to new book record.
                resObj = {
                    "res": contract.url
                };
                res.status(200).send(JSON.stringify(resObj));
                // res.redirect();
            });

        });

    },
];
  1. 레코드를 갱신합니다.blk_data를 참조하십시오.
// Post lender accept borrow proposal.
exports.ctr_contract_propose_accept_post = [

    // Validate fields
    body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
    body('contract_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
    body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),

    // Sanitize fields.
    sanitizeBody('*').escape(),
    // Process request after validation and sanitization.
    (req, res, next) => {

        // Extract the validation errors from a request.
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            // There are errors. Render form again with sanitized values/error messages.
            res.status(400).send({ errors: errors.array() });
            return;
        }

        // Create a Book object with escaped/trimmed data
        var book_fields =
            {
                _id: req.body.book_id, // This is required, or a new ID will be assigned!
                status: 'on_loan'
            };

        // Create a contract object with escaped/trimmed data
        var contract_fields = {
            $push: {
                blk_data: {
                    tx_addr: req.body.tx_addr,
                    block_number: req.body.block_number
                }
            }
        };

        async.parallel({
            //call the function get book model
            book: function(callback) {
                Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
            },
            contract: function(callback) {
                Contract.findByIdAndUpdate(req.body.contract_id, contract_fields, {}).exec(callback);
            },
        }, function(error, results) {
            if (error) {
                res.status(400).send({ errors: errors.array() });
                return;
            }

            if ((results.book.isNew) || (results.contract.isNew)) {
                res.status(400).send({ errors: errors.array() });
                return;
            }

            var resObj = {
                "res": results.contract.url
            };
            res.status(200).send(JSON.stringify(resObj));
        });
    },
];

답장 감사합니다.

첫 번째 방법을 시도해 봤지만 변한 게 없어요.그리고 나서, 나는 결과를 기록하려고 했다.데이터가 표시되는 위치에 도달할 때까지 한 단계씩 드릴다운했습니다.

잠시 후 문제를 발견했습니다. 저는 그것을 로 변환하고 ..toString().

나는 그것을 고쳤고 지금은 훌륭하게 작동한다.잘못된 경보에 대해 죄송합니다.

언급URL : https://stackoverflow.com/questions/19695058/how-to-define-object-in-array-in-mongoose-schema-correctly-with-2d-geo-index

반응형