首页 > 解决方案 > 如何在 Schema 中发布 Schema 数组?

问题描述

我有两种模式,一种叫做position另一种叫做path. 基本上,我想要路径schema来保存一组position模式。

首先,这是我的position架构:

const mongoose = require('mongoose');
var Schema = mongoose.Schema;

var positionSchema = new Schema({
    position : {
        x : Number,
        y : Number
    },
    orientation : {
        x : Number
    }
});

var Position = mongoose.model('Position', positionSchema);
module.exports = Position

简单的一个,只保存一些浮点数。然后,这是我的path模式,它就像position模式的父亲:

const mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Position = require('./position');

var pathSchema = new Schema({
    path : [{type: Schema.ObjectId, ref: 'Position'}]
});

module.exports = mongoose.model("Path", pathSchema);

所以现在,我想使用 Postman 将一些位置数组发布到路径模式,代码如下所示:

router.post("/", (req,res,next)=>{
    const _path = new Path({
        path : req.body.path
    })
    .save()
    .then(docs => {
        const response = {
            status: 201,
            message: "Path has been added succesfully",
            path_ID: docs.path_id,
            path : docs.path
        };
        res.status(201).json(response);
    })
    .catch(err => {
        res.status(500).json({
            message: err
        });
    });
});

但是当我在 Postman 中使用这个例子时:

{"path" : [
    {"position" : { "x": "1111", "y" : "2222"}, "orientation" : { "x":"0"} },
{"position" : { "x": "1111", "y" : "2222"}, "orientation" : { "x":"0"} }
]}

我收到一个错误:

 {
    "message": {
        "errors": {
            "path": {
                "message": "Cast to Array failed for value \"[ { position: { x: '1111', y: '2222' }, orientation: { x: '0' } },\n  { position: { x: '1111', y: '2222' }, orientation: { x: '0' } } ]\" at path \"path\"",
                "name": "CastError",
                "stringValue": "\"[ { position: { x: '1111', y: '2222' }, orientation: { x: '0' } },\n  { position: { x: '1111', y: '2222' }, orientation: { x: '0' } } ]\"",
                "kind": "Array",
                "value": [
                    {
                        "position": {
                            "x": "1111",
                            "y": "2222"
                        },
                        "orientation": {
                            "x": "0"
                        }
                    },
                    {
                        "position": {
                            "x": "1111",
                            "y": "2222"
                        },
                        "orientation": {
                            "x": "0"
                        }
                    }
                ],
                "path": "path",
                "reason": {
                    "message": "Cast to ObjectId failed for value \"{ position: { x: '1111', y: '2222' }, orientation: { x: '0' } }\" at path \"path\"",
                    "name": "CastError",
                    "stringValue": "\"{ position: { x: '1111', y: '2222' }, orientation: { x: '0' } }\"",
                    "kind": "ObjectId",
                    "value": {
                        "position": {
                            "x": "1111",
                            "y": "2222"
                        },
                        "orientation": {
                            "x": "0"
                        }
                    },
                    "path": "path"
                }
            }
        },
        "_message": "Path validation failed",
        "message": "Path validation failed: path: Cast to Array failed for value \"[ { position: { x: '1111', y: '2222' }, orientation: { x: '0' } },\n  { position: { x: '1111', y: '2222' }, orientation: { x: '0' } } ]\" at path \"path\"",
        "name": "ValidationError"
    }
}

所以我想这与我的 post 方法有关,因为我的服务器无法正确识别 post 消息并等待其他内容。

我在这里做错了什么?

标签: node.jsexpressmongoose

解决方案


pathinside是对文档pathSchema的引用数组。Position这意味着在您尝试为其分配对象数组时path必须存储一个数组。ObjectId您必须先保存Position',然后再将它们的_id值推送到path数组:

router.post("/", (req,res,next)=>{
    const savePositions = req.body.path.map(position => {          // create promises that save Position documents
        return new Position(position).save();
    });

    Promise.all(savePositions)                                     // run all save promises in parallel
      .then(positions => positions.map(position => position._id))  // get an array of ids of saved documents
      .then(positionsIds => new Path({ path: positionsIds }).save())
      .then(savedPath => {
        // do the job with saved Path
      })
      .catch(err => {
        // handle the error
    });
});

推荐阅读