简体   繁体   中英

How to add save another Schema data to a model?

I am using mongoose with Mongodb v3.4.3

Below is my image model code

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],
});

Below is my CoordinateSchema code

const mongoose = require("mongoose");

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

module.exports =  CoordinateSchema;

Below is my api js code running on express,

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

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


       })
    });

How to finish this code so I can store coordinates data in Image model.

Thanks.

UPDATE

To update the coordinates inside of findOneAndUpdate, you simply check that the returned document isn't undefined (which would mean your image wasn't found). Modify your api.js code like so:

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');
    );
});

Here's my guess why it isn't working.

In ImageSchema , you are sub-nesting an array of CoordinateSchema . But CoordinateSchema is a document which already contains an array .

This is probably not what you're looking for. If you're using mongoose version 4.2.0 or higher , you can nest CoordinateSchema inside of ImageSchema as a single document. Re-write your ImageSchema like this:

// ...

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

If this didn't work or doesn't resolve your issue, please let me know so we can work together to find a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM