2017-07-30 68 views
0

我使用的猫鼬用MongoDB的v3.4.3如何将另一个架构数据添加到模型中?

下面是我的图像模型代码

const mongoose = require("mongoose"); 
const CoordinateSchema = require("./coordinate"); 

const ImageSchema = new mongoose.Schema({ 
    image_filename: { 
     type: String, 
     required: true 
    }, 
    image_url: { 
     type: String, 
     required: true 
    }, 
    coordinates: [CoordinateSchema], 
}); 

下面是我CoordinateSchema代码

const mongoose = require("mongoose"); 

const CoordinateSchema = new mongoose.Schema({ 
    coordinates : { 
     type: Array, 
     default: [], 
    } 
}); 

module.exports = CoordinateSchema; 

下面是在快递运行我的API的js代码,

router.post('/receiveCoordinates.json', (req, res, next) => { 

     Image.findOneAndUpdate({image_filename:req.body.file_name}).then((image) => { 


     }) 
    }); 

如何完成此代码,所以我c商店坐标数据在图像模型中。

谢谢。

+0

你使用什么版本的猫鼬? –

+0

@JoseLopezGarcia我正在使用Mongodb v3.4.3。我更新了问题,我发现我可以使用findOneAndUpdate – Dreams

+0

我问你的猫鼬版本,而不是MongoDB!顺便检查我的答案,如果它不起作用,让我知道,所以我们可以制定一个解决方案 –

回答

1

UPDATE

要更新findOneAndUpdate内的坐标,只需检查返回的文件是不是不确定的(这将意味着你的图片未找到)。修改您的api.js代码如下所示:

router.post('/receiveCoordinates.json', (req, res, next) => { 
    Image.findOneAndUpdate({image_filename:req.body.file_name}).then((image) => { 
     if (!image) return Promise.reject(); //Image not found, reject the promise 
     image.where({_id: parent.children.id(_id)}).update({coordinates: req.body.coordinates}) //Needs to be an array 
      .then((coords) => { 
       if (!coords) return Promise.reject(); 
       //If you reach this point, everything went as expected 
      }); 
    }).catch(() => { 
     console.log('Error occurred'); 
    ); 
}); 

这里是我的猜测,为什么它不工作。

ImageSchema中,您正在亚嵌套一组CoordinateSchema。但CoordinateSchema是一个文档,其中已经包含数组

这可能不是你要找的。如果您使用的是猫鼬版本4.2.0或更高版本,则可以将ImageSchema中的CoordinateSchema作为单个文档嵌套。重新写你的ImageSchema这样的:

// ... 

const ImageSchema = new mongoose.Schema({ 
    // ... 
    coordinates: CoordinateSchema, 
}); 

如果没有工作或者没有解决您的问题,请让我知道,所以我们可以共同努力,找到一个解决方案。

+0

谢谢你。我更新了我发现可以使用findOneAndUpdate但不知道如何完成的问题 – Dreams

+0

找到之后你想要做什么? –

+0

我想更新图像记录中的坐标数据。 – Dreams

相关问题