Javascript 如何将另一个架构数据添加到模型中?
我在Mongodb v3.4.3中使用mongoose 下面是我的图像模型代码Javascript 如何将另一个架构数据添加到模型中?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我在Mongodb v3.4.3中使用mongoose 下面是我的图像模型代码 const mongoose = require("mongoose"); const CoordinateSchema = require("./coordinate"); const ImageSchema = new mongoose.Schema({ image_filename: { type: String, required: true }, i
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],
});
下面是我的协调代码
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是一个已经包含数组的文档
这可能不是你想要的。如果您使用的是MongooseVersion4.2.0或更高版本,则可以将CoordinateSchema作为单个文档嵌套在ImageSchema中。重新编写ImageSchema,如下所示:
// ...
const ImageSchema = new mongoose.Schema({
// ...
coordinates: CoordinateSchema,
});
如果这不起作用或无法解决您的问题,请让我知道,以便我们可以一起找到解决方案。您使用的是什么版本的mongoose?@JoseLopezGarcia我使用的是Mongodb v3.4.3。我更新了这个问题,我发现我可以使用FindONEANDUPDATE。我问的是你的mongoose版本,不是MongoDB!顺便问一下,请检查我的答案,如果不起作用,请告诉我,这样我们就可以找到解决方案。谢谢。我更新了我发现我可以使用findOneAndUpdate但不知道如何完成的问题。找到一个问题后你想做什么?好的,我会修改答案。我在脑海中写下了更新(我正在旅行,没有带工作站)。试试代码,告诉我它给你带来了什么错误,如果有人真的很感激的话!