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

nie*_*s_h 106 schema geo mongoose mongodb node.js

我目前在为下面的文档创建架构时遇到问题.来自服务器的响应始终将"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
    }]
    }
}
Run Code Online (Sandbox Code Playgroud)

猫鼬模式:

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

Chrome中"网络"标签的响应总是如此(这只是错误的trk部分):

{ trk: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
Run Code Online (Sandbox Code Playgroud)

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

  1. trk:Schema.Types.Mixed
  2. trk:[Schema.Types.Mixed]
  3. trk:[{type:[Number],index:"2d"}]

希望你能帮我 ;-)

Kun*_*ndu 197

您可以通过以下方式声明trk: - 或者

trk : [{
    lat : String,
    lng : String
     }]
Run Code Online (Sandbox Code Playgroud)

要么

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 
  }
});
Run Code Online (Sandbox Code Playgroud)

或者您可以设置对象数组

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'
      }
});
Run Code Online (Sandbox Code Playgroud)

  • trk:{type:Array,"default":[]}最适合我!它简单而优雅! (3认同)

Pie*_*oui 59

我和猫鼬有类似的问题:

fields: 
    [ '[object Object]',
     '[object Object]',
     '[object Object]',
     '[object Object]' ] }
Run Code Online (Sandbox Code Playgroud)

事实上,我在我的架构中使用"type"作为属性名称:

fields: [
    {
      name: String,
      type: {
        type: String
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]
Run Code Online (Sandbox Code Playgroud)

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

fields: [
    {
      name: String,
      type: {
        type: { type: String }
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]
Run Code Online (Sandbox Code Playgroud)

  • 好吧,是的,甚至都没想过.这就解决了我的问题就在我即将开始抨击桌面上的东西之前哈哈再次感谢.从现在开始,我将在我的猫鼬模式中避免'输入'. (4认同)
  • 或者您可以将 typeKey 选项传递给架构构建器以覆盖类型声明 (2认同)

小智 12

为了在模式中创建一个数组,我们必须再创建一个模式,用于monetizationSchema一次存储一个数据,另一个用于存储另一个数据,因为blogSchema我们有monetization包含monetizationSchema在方括号中的字段作为数组。

Schema用于一次存储一个数据。

const monetizationSchema = new Schema({
      amazonUrl: {
        type: String,
        required: true,
      } 
    });
Run Code Online (Sandbox Code Playgroud)

架构monetization作为数组。

const blogSchema = {
  monetization: [
   monetizationSchema
  ],
  image: {
   type: String,
   required: true
  },
  // ... etc
});
Run Code Online (Sandbox Code Playgroud)


Man*_*ana 9

您可以如下声明一个数组

trk : [{
    lat : String,
    lng : String
}]
Run Code Online (Sandbox Code Playgroud)

但它会将(空数组)设置[]为默认值。

如果您不想要这个默认值,那么要覆盖这个默认值,您需要将默认值设置为undefined如下

trk: {
    type: [{
        lat : String,
        lng : String
    }],
    default: undefined
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我需要解决的问题是存储包含几个字段(address、book、num_of_days、borrower_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
        }]
    }
);
Run Code Online (Sandbox Code Playgroud)
  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();
            });

        });

    },
];
Run Code Online (Sandbox Code Playgroud)
  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));
        });
    },
];
Run Code Online (Sandbox Code Playgroud)