mongodb 如何使用二维geo索引正确定义Mongoose模式中数组中的对象

thtygnil  于 2023-03-01  发布在  Go
关注(0)|答案(6)|浏览(138)

我目前在为下面的文档创建模式时遇到了问题。服务器的响应总是以[Object]的形式返回"trk"字段值。不知何故,我不知道这应该如何工作,因为我尝试了至少所有对我有意义的方法;-)
如果这有帮助的话,我的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],

我已经尝试了不同的Schema定义"trk":

  1. trk:架构.类型.混合
  2. trk:[架构.类型.混合]
  3. trk:[{类型:[编号],索引:"2d "}]
    希望你能帮助我;-)
xmjla07d

xmjla07d1#

您可以通过以下方式声明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 
  }
});

也可以通过以下方式设置对象的Array

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'
      }
});
xqnpmsa8

xqnpmsa82#

我对 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
    }
  ]
b4qexyjb

b4qexyjb3#

为了在模式中创建数组,我们必须再创建一个模式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
});
sqserrrh

sqserrrh4#

可以按如下方式声明数组

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

但是它将把[](空数组)设置为默认值。
如果不希望使用此默认值,然后覆盖此默认值,则需要将默认值设置为undefined,如下所示

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

zxlwwiss5#

我需要解决的问题是存储包含几个字段的合同(地址,图书,天数,借款人地址,blk数据),blk数据是一个交易列表(区块号和交易地址)。这个问题和答案帮助了我。我想分享我的代码如下。希望这能有所帮助。
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));
        });
    },
];
xmakbtuz

xmakbtuz6#

感谢您的回复。
我尝试了第一种方法,但没有任何变化。然后,我尝试记录结果。我只是一级一级地向下钻取,直到我最终到达数据正在显示的地方。
过了一会儿我发现了问题:当我发送响应时,我通过.toString()将其转换为字符串。
我修好了,现在它工作得很出色。抱歉误报了。

相关问题