gpt4 book ai didi

javascript - 如何添加保存另一个模式数据到模型中?

转载 作者:行者123 更新时间:2023-12-03 03:45:44 26 4
gpt4 key购买 nike

我正在使用 mongoose 和 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],
});

下面是我的坐标架构代码

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中,您正在子嵌套一个数组CooperativeSchema。但 CoordinateSchema 是一个已包含数组的文档。

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

// ...

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

如果这不起作用或无法解决您的问题,请告诉我,以便我们共同寻找解决方案。

关于javascript - 如何添加保存另一个模式数据到模型中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45400133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com