如何使用2d地理索引在Mongoose模式中正确定义数组中的对象


113

我目前在为下面的文档创建架构时遇到问题。服务器的响应始终将“ 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
    }]
    }
}

猫鼬架构:

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

Chrome中“网络”标签中的响应始终如下所示(这只是trk-part错了):

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

我已经尝试过为“ trk”使用不同的架构定义:

  1. trk:Schema.Types.Mixed
  2. trk:[Schema.Types.Mixed]
  3. trk:[{类型:[数字],索引:“ 2d”}]

希望你能帮我 ;-)

Answers:


219

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

任何想法如何在这种情况下命名html字段,即万一我们需要在数据库中存储一个javascript对象数组?例如,将字段命名为trk.lattrk.lng在html中将不起作用。
Raeesaa 2014年

3
trk:{type:Array,“ default”:[]}最适合我!简单而优雅!
spiralmoon14年

1
@DpGeek如果您以该格式声明数组,则无法直接更新数组字段。为了直接更新数组,我使用了{lat:String,lng:String}子模式。如果您不希望使用该功能,那么trk:{type:Array,“ default”:[]}将是最好的,否则必须声明子模式。
昆都

默认,不带引号对我trk : { type : Array , default : ['item1', 'item2'] }
有用

1
如果将'lat'和'lng'字段定义为Number而不是string,它仍然可以工作吗?
jimijazz

63

我的猫鼬也有类似的问题:

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

实际上,我在架构中使用“类型”作为属性名称:

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

为了避免这种行为,您必须将参数更改为:

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

4
是的,是的,甚至都没有考虑过。这就解决了我的问题,就在我要开始猛击桌子上的东西之前,哈哈,再次感谢。从现在开始,我将避免在猫鼬模式中使用“类型”。
blackops,2015年

您能否举一个您要插入的json的示例?
owensmartin

1
或者您可以将typeKey选项传递给模式生成器以覆盖类型声明
jimijazz

2

感谢您的答复。

我尝试了第一种方法,但没有改变。然后,我尝试记录结果。我只是逐级向下钻取,直到最终到达显示数据的位置。

一段时间后,我发现了问题:发送响应时,我通过将该响应转换为字符串.toString()

我已经解决了,现在效果很好。对不起,误报警。


1

我需要解决的问题是存储包含一些字段的合同(地址,书,num_of_days,借款人地址,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));
        });
    },
];
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.