我在 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;
下面是我在 express 上运行的 api js 代码,
router.post('/receiveCoordinates.json', (req, res, next) => {
Image.findOneAndUpdate({image_filename:req.body.file_name}).then((image) => {
})
});
如何完成此代码以便我可以在图像模型中存储坐标数据。
谢谢。
更新
要更新 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 是一个已经包含数组的文档。
这可能不是您要找的。如果您使用的是 mongoose版本 4.2.0 或更高版本,则可以将 CoordinateSchema 作为单个文档嵌套在 ImageSchema 中。像这样重写你的 ImageSchema:
// ...
const ImageSchema = new mongoose.Schema({
// ...
coordinates: CoordinateSchema,
});
如果这不起作用或不能解决您的问题,请告诉我,以便我们共同寻找解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句