最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何保持蒙戈的数组索引从更新期间更改?

IT培训 admin 5浏览 0评论

如何保持蒙戈的数组索引从更新期间更改?

我想更新我的对象中的数组。然而,每一次我发帖子呼吁,在阵列的变化指标。

我曾尝试使用$设置和手动更新阵列...但阵列上的指数在不断变化。

这里是模型:

const MappedImageSchema = new Schema({
    imageUrl: {type: String, required: true},
    name: {type: String, required: true},
    areas:[
        {
            name: {type: String},
            shape: {type: String},
            coords:[{type: Number}],
        }
    ]
});
module.exports = MappedImage = mongoose.model('mappedImages', MappedImageSchema)

下面是执行更新的代码:

// @route   POST api/maps/:id/areas
// @desc    add an area to a map (by map id)
// @access  Private
router.post('/:id/areas/:id_area', passport.authenticate('jwt', { session: false }),
    (req, res) => {

        MappedImage.findById(req.params.id)
        .then(map => {

            // get all of the areas from the map...
            var allAreas = map.areas;

            // now get the index of the area we are going to update
            const areaIndex = map.areas.map(item => item._id.toString()).indexOf(req.params.id_area);

            // update the information
            var coords = req.body.coords.split(',');
            const updatedArea = {
                name: req.body.name,
                shape: req.body.shape,

                coords: coords,
            };

            // set the updated information in the correct map area
            allAreas[areaIndex] = updatedArea;

            var query = {_id: req.params.id}; // this is the MAP id
            var update = {$set: {areas:allAreas}};  // update the areas 
            var options = {new: true};

            MappedImage.findOneAndUpdate(query, update, options)
            .then(map => res.json(map))
            .catch(err => res.status(404).json({ mapnotfound: err }));

        })
        .catch(err => res.status(404).json({ mapnotfound: 'Map not found while updating area' }));
    }
  );

这里是调用之前的数据

{
    "_id": "5c5c69dda40e872258b4531d",
    "imageUrl": "url test",
    "name": "name test",
    "areas": [
        {
        "coords": [1,2,3,4,5,6],
        "_id": "5c5c8db2f904932dd8d4c560",  <---- _id changes every time !
        "name": "area name",
        "shape": "poly"
        }
    ],
    "__v": 3
}

这里是邮差呼叫我做:

调用的结果是名义得到改变......但这样做索引...使得下次调用失败,并“与指数没有发现区”。

什么是令人困惑的这个问题是地图中的_id当我运行这段代码没有更新:

router.post('/:id', passport.authenticate('jwt', { session: false }),
(req, res) => {

    var query = {_id: req.params.id};
    var update = {imageUrl: req.body.imageUrl, name: req.body.name};
    var options = {new: true};

    MappedImage.findOneAndUpdate(query, update, options)
    .then(map => res.json(map))
    .catch(err => res.status(404).json({ mapnotfound: err }));
});

更新1

我尝试使用面积指数和更新只是该区域...但这段代码的_id的变化,以及:

        ... same code all the way down to here
        allAreas[areaIndex] = updatedArea;

        // but instead of calling 'findOneAndUpdate'... call map save
        map.save().then(map => res.json(map));

更新2

我不能让这样的代码为areas._id和地区工作。$是不确定的?

var query = {_id: req.params.id, areas._id: id_area}; // this is the MAP id
var update = {$set: {areas.$: updatedArea}};  // update the area

更新3

所以,把_id在updatedArea解决这个问题......但“感觉”不对这样做:(每EOL答案)

        const updatedArea = {
            _id: req.params.id_area,
            name: req.body.name,
            shape: req.body.shape,

            coords: coords,
        };

更新4

EOL - 感谢对MongoDB的侧面验证......如果解决了DB ID的问题...我只需要知道为什么我的查询失败。我想这和所有我在终端输出“创建查询”看到...我从来没有看到“查询”,它的定义...所以什么是错的,我不知道如何找出什么。以下是我现在有:

 console.log('creating query');
 var query = {"_id": req.params.id, "areas._id": id_area};
 console.log('query');
 console.log(query);

更新5想通了,为什么没有输出的查询,id_area没有定义...但req.params.id_area是!

 console.log('creating query');
 var query = {"_id": req.params.id, "areas._id": req.params.id_area};
 console.log('query');

更新6

代码是...但它仍然没有工作。一张图片胜过一千个词......所以这里有两个:

这一个显示区域ID仍会发生变化:

这里是我现在的代码:

    console.log('Update area');
    console.log('changing area ' + req.params.id_area);
    //console.log(req.body);

    const { errors, isValid } = mapValidators.validateAreaInput(req.body);

    // Check Validation
    if(!isValid){
        return res.status(400).json(errors);
    }

    MappedImage.findById(req.params.id)
    .then(map => {

        // Check to see if area exists
        if (
            map.areas.filter(
            area => area._id.toString() === req.params.id_area
            ).length === 0
        ) {
            return res.status(404).json({ areanotfound: 'Area does not exist' });
        }

        console.log('area exists');

        // get all of the areas from the map...
        var allAreas = map.areas;

        console.log('all areas');
        console.log(allAreas);

        // now get the index of the area we are going to update
        const areaIndex = map.areas.map(item => item._id.toString()).indexOf(req.params.id_area);

        console.log('area index');
        console.log(areaIndex);

        // update the information
        var coords = req.body.coords.split(',');
        const updatedArea = {
            name: req.body.name,
            shape: req.body.shape,
            preFillColor: req.body.preFillColor,
            fillColor: req.body.fillColor,

            coords: coords,
        };

        console.log('updated area');
        console.log(updatedArea);


        // set the updated information in the maps areas
        allAreas[areaIndex] = updatedArea;

        console.log('creating query');
        var query = {"_id": req.params.id, "areas._id": req.params.id_area};
        console.log('query');
        console.log(query);


        var update = {$set: {"areas.$": updatedArea}};
        console.log('update');
        console.log(update);

        var options = {new: true};

        MappedImage.findOneAndUpdate(query, update, options)
        .then(map => res.json(map))
        .catch(err => res.status(404).json({ mapnotfound: err }));

    })
    .catch(err => res.status(404).json({ mapnotfound: 'Map not found while updating area' }));

这里是终端输出:

回答如下:

你可以尝试设置在_id对象updatedArea属性与你想更新区域的价值。这将防止在使用$set运营商创建一个新的ID。事情是这样的:

// now get the index of the area we are going to update
const areaIndex = map.areas.map(item => item._id.toString()).indexOf(req.params.id_area);

// update the information
var coords = req.body.coords.split(',');
const updatedArea = {
        _id: id_area,
        name: req.body.name,
        shape: req.body.shape,
        coords: coords,
};
...

请注意,上述解决方案你总是设置一个新的数组,这就是为什么会产生新的ID。

你也可以尝试使用$ operator更新特定元素的数组中:

var query = {"_id": req.params.id, "areas._id": id_area}; // this is the MAP id
var update = {$set: {"areas.$": updatedArea}};  // update the area

请参见下面的屏幕截图的例子(执行在mongodb的壳中的命令),其中我试图仅更新所述第二阵列元件(即,具有_id 5c5c8db2f904932dd8d4c561

如何保持蒙戈的数组索引从更新期间更改?

我想更新我的对象中的数组。然而,每一次我发帖子呼吁,在阵列的变化指标。

我曾尝试使用$设置和手动更新阵列...但阵列上的指数在不断变化。

这里是模型:

const MappedImageSchema = new Schema({
    imageUrl: {type: String, required: true},
    name: {type: String, required: true},
    areas:[
        {
            name: {type: String},
            shape: {type: String},
            coords:[{type: Number}],
        }
    ]
});
module.exports = MappedImage = mongoose.model('mappedImages', MappedImageSchema)

下面是执行更新的代码:

// @route   POST api/maps/:id/areas
// @desc    add an area to a map (by map id)
// @access  Private
router.post('/:id/areas/:id_area', passport.authenticate('jwt', { session: false }),
    (req, res) => {

        MappedImage.findById(req.params.id)
        .then(map => {

            // get all of the areas from the map...
            var allAreas = map.areas;

            // now get the index of the area we are going to update
            const areaIndex = map.areas.map(item => item._id.toString()).indexOf(req.params.id_area);

            // update the information
            var coords = req.body.coords.split(',');
            const updatedArea = {
                name: req.body.name,
                shape: req.body.shape,

                coords: coords,
            };

            // set the updated information in the correct map area
            allAreas[areaIndex] = updatedArea;

            var query = {_id: req.params.id}; // this is the MAP id
            var update = {$set: {areas:allAreas}};  // update the areas 
            var options = {new: true};

            MappedImage.findOneAndUpdate(query, update, options)
            .then(map => res.json(map))
            .catch(err => res.status(404).json({ mapnotfound: err }));

        })
        .catch(err => res.status(404).json({ mapnotfound: 'Map not found while updating area' }));
    }
  );

这里是调用之前的数据

{
    "_id": "5c5c69dda40e872258b4531d",
    "imageUrl": "url test",
    "name": "name test",
    "areas": [
        {
        "coords": [1,2,3,4,5,6],
        "_id": "5c5c8db2f904932dd8d4c560",  <---- _id changes every time !
        "name": "area name",
        "shape": "poly"
        }
    ],
    "__v": 3
}

这里是邮差呼叫我做:

调用的结果是名义得到改变......但这样做索引...使得下次调用失败,并“与指数没有发现区”。

什么是令人困惑的这个问题是地图中的_id当我运行这段代码没有更新:

router.post('/:id', passport.authenticate('jwt', { session: false }),
(req, res) => {

    var query = {_id: req.params.id};
    var update = {imageUrl: req.body.imageUrl, name: req.body.name};
    var options = {new: true};

    MappedImage.findOneAndUpdate(query, update, options)
    .then(map => res.json(map))
    .catch(err => res.status(404).json({ mapnotfound: err }));
});

更新1

我尝试使用面积指数和更新只是该区域...但这段代码的_id的变化,以及:

        ... same code all the way down to here
        allAreas[areaIndex] = updatedArea;

        // but instead of calling 'findOneAndUpdate'... call map save
        map.save().then(map => res.json(map));

更新2

我不能让这样的代码为areas._id和地区工作。$是不确定的?

var query = {_id: req.params.id, areas._id: id_area}; // this is the MAP id
var update = {$set: {areas.$: updatedArea}};  // update the area

更新3

所以,把_id在updatedArea解决这个问题......但“感觉”不对这样做:(每EOL答案)

        const updatedArea = {
            _id: req.params.id_area,
            name: req.body.name,
            shape: req.body.shape,

            coords: coords,
        };

更新4

EOL - 感谢对MongoDB的侧面验证......如果解决了DB ID的问题...我只需要知道为什么我的查询失败。我想这和所有我在终端输出“创建查询”看到...我从来没有看到“查询”,它的定义...所以什么是错的,我不知道如何找出什么。以下是我现在有:

 console.log('creating query');
 var query = {"_id": req.params.id, "areas._id": id_area};
 console.log('query');
 console.log(query);

更新5想通了,为什么没有输出的查询,id_area没有定义...但req.params.id_area是!

 console.log('creating query');
 var query = {"_id": req.params.id, "areas._id": req.params.id_area};
 console.log('query');

更新6

代码是...但它仍然没有工作。一张图片胜过一千个词......所以这里有两个:

这一个显示区域ID仍会发生变化:

这里是我现在的代码:

    console.log('Update area');
    console.log('changing area ' + req.params.id_area);
    //console.log(req.body);

    const { errors, isValid } = mapValidators.validateAreaInput(req.body);

    // Check Validation
    if(!isValid){
        return res.status(400).json(errors);
    }

    MappedImage.findById(req.params.id)
    .then(map => {

        // Check to see if area exists
        if (
            map.areas.filter(
            area => area._id.toString() === req.params.id_area
            ).length === 0
        ) {
            return res.status(404).json({ areanotfound: 'Area does not exist' });
        }

        console.log('area exists');

        // get all of the areas from the map...
        var allAreas = map.areas;

        console.log('all areas');
        console.log(allAreas);

        // now get the index of the area we are going to update
        const areaIndex = map.areas.map(item => item._id.toString()).indexOf(req.params.id_area);

        console.log('area index');
        console.log(areaIndex);

        // update the information
        var coords = req.body.coords.split(',');
        const updatedArea = {
            name: req.body.name,
            shape: req.body.shape,
            preFillColor: req.body.preFillColor,
            fillColor: req.body.fillColor,

            coords: coords,
        };

        console.log('updated area');
        console.log(updatedArea);


        // set the updated information in the maps areas
        allAreas[areaIndex] = updatedArea;

        console.log('creating query');
        var query = {"_id": req.params.id, "areas._id": req.params.id_area};
        console.log('query');
        console.log(query);


        var update = {$set: {"areas.$": updatedArea}};
        console.log('update');
        console.log(update);

        var options = {new: true};

        MappedImage.findOneAndUpdate(query, update, options)
        .then(map => res.json(map))
        .catch(err => res.status(404).json({ mapnotfound: err }));

    })
    .catch(err => res.status(404).json({ mapnotfound: 'Map not found while updating area' }));

这里是终端输出:

回答如下:

你可以尝试设置在_id对象updatedArea属性与你想更新区域的价值。这将防止在使用$set运营商创建一个新的ID。事情是这样的:

// now get the index of the area we are going to update
const areaIndex = map.areas.map(item => item._id.toString()).indexOf(req.params.id_area);

// update the information
var coords = req.body.coords.split(',');
const updatedArea = {
        _id: id_area,
        name: req.body.name,
        shape: req.body.shape,
        coords: coords,
};
...

请注意,上述解决方案你总是设置一个新的数组,这就是为什么会产生新的ID。

你也可以尝试使用$ operator更新特定元素的数组中:

var query = {"_id": req.params.id, "areas._id": id_area}; // this is the MAP id
var update = {$set: {"areas.$": updatedArea}};  // update the area

请参见下面的屏幕截图的例子(执行在mongodb的壳中的命令),其中我试图仅更新所述第二阵列元件(即,具有_id 5c5c8db2f904932dd8d4c561

发布评论

评论列表 (0)

  1. 暂无评论