使用objectId引用数组保持mongoose模型

问题描述 投票:0回答:1

我正在使用mongoDB来满足我的restful API的持久性需求。

我有一个带有导出模型的事件模式。我还有一个带有导出模型的Location模式。

Event在其模式中有一组Locations,表示oneToMany关系。

我向我的API发出HTTP POST请求以使用相关位置列表保留事件,如下所示:

{
"name": "My first advertised event",
"shortDescription": "Some kind of event",
"fullDescription": "This is a massive detailed description of an event, honestly.",
"location": [
    "5a49121b4f1e572d48785ddd", 
    "2e21b4f1e572d48785dcb"
    ]

}

我得到以下错误,我可以;似乎找到一个解决方案:

        "_message": "Event validation failed",
    "message": "Event validation failed: location: Cast to Array failed for value \"[ '5a49121b4f1e572d48785ddd', '2e21b4f1e572d48785dcb' ]\" at path \"location\"",
    "name": "ValidationError"

我的相关模式和服务如下:

const mongoose = require('mongoose');
const Location = require('./location');

const EventSchema = new mongoose.Schema({
    name: String,
    shortDescription: String,
    fullDescription: String,
    location : [
        { type: mongoose.Schema.ObjectId,
            ref: 'Location' }
        ]
}, {
    timestamps: true
});

mongoose.model('Event', EventSchema);

module.exports = mongoose.model('Event');

const mongoose = require('mongoose');
const GeoLocation = require('../common/mongoose/model/geoLocation').geoLocation();

const LocationSchema = new mongoose.Schema({
    name: String,
    description: String,
    location : GeoLocation
}, {
    timestamps: true
});

mongoose.model('Location', LocationSchema);

module.exports = mongoose.model('Location');
const Hal = require('hal');
const Event = require('./event.js');

module.exports = {

createNewEvent: (req, res) => {
    let locations = [];
    req.body.location.map(loc => locations.push(loc));
   var event = new Event({
        name : req.body.name,
        shortDescription : req.body.shortDescription,
        fullDescription : req.body.fullDescription,
        location : req.body.location
    });
   event.save()
        .catch(err => res.status(500).send({message: err}))
        .then(data => res.send(data)
        );
    },
}

我一直试图解决这个问题好几个小时但似乎无法解决这个问题。如果我在json中使用单个引用进行保存,那么它可以工作,甚至认为Event模式需要oneToMany关系。

我对mongoDB相当新,所以我接受我可能错过了一个基本概念。如果有人能帮助我了解我做错了什么,我会非常感激。

还有,新年快乐! :)

javascript node.js mongodb express mongoose
1个回答
0
投票

我需要修改我的服务电话:

    createNewEvent: (req, res) => {
   var event = new Event({
        name : req.body.name,
        shortDescription : req.body.shortDescription,
        fullDescription : req.body.fullDescription,
    });
    req.body.location.map(x => event.location.push(x));
    event.save()
        .catch(err => res.status(500).send({message: err}))
        .then(data => res.send(data)
        );
}
© www.soinside.com 2019 - 2024. All rights reserved.