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

标签 javascript node.js mongodb express mongoose

我正在使用 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/

相关文章:

mongodb - 有没有办法恢复或撤消副本集配置

javascript - 使用按钮显示/隐藏 DIV 控件

javascript - 检测网站是否被直接访问..可能吗?

javascript - Aerospike 使用 JavaScript 连接

javascript - node.js 错误 : req. flash() 需要 session

node.js - Azure MongoDB find操作查询时间很慢

python - 删除mongodb中的重复值

javascript - 删除最后一个字符串的逗号

javascript - 调用两个 JS 函数并同步它们(snakeAnim 和 Animated Marker)

node.js - 我的 npm-lint 抛出错误 "missing script: lint"