Mongoose无法将新的obejct推送到父数组

时间:2018-02-09 21:07:20

标签: node.js mongodb express asynchronous mongoose

我有以下猫鼬模型:

Place.js

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const placeSchema = new Schema({
    title: { type: String, require: true },
    filename: { type: String, require: true },
    lociSets: [{ type: Schema.Types.ObjectId, ref: 'LociSet'}]
})

module.exports = mongoose.model("places", placeSchema)

LociSet.js

const mongoose = require("mongoose")
const Schema = mongoose.Schema
const LociSchema = require('./Locus')

const lociSetSchema = new Schema({
    title: { type: String, require: true },
    creator: { type: Schema.Types.ObjectId, ref: 'User' },
    public: { type: Boolean, default: true },
    loci: [LociSchema]
})
module.exports = mongoose.model("lociSets", lociSetSchema)

Locus.js

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const locusSchema = new Schema({
    position: {
        x: { type: Number, require: true },
        y: { type: Number, require: true },
        z: { type: Number, require: true }
    }
})

module.exports = locusSchema

问题: 我尝试将一个新的LociSet插入到Place的lociSet数组中,如下所示:

exports.createOne = async (req, res) => {
    const {
        title,
        public = true,
        loci = []
    } = req.body

    console.log(title,public,loci,req.user.id)
    const lociSet = new LociSet({
        title,
        public,
        loci,
        creator: req.user.id
    })

    try {
        const place = await Place.findOne({
            "title": req.params.title.toLowerCase()
        })

        console.log(lociSet)

        await lociSet.save()
        await place.lociSets.push(lociSet)
        await place.save()
    } catch (err) {
        res.status(500).send({
            message: "Some error occurred while creating the loci set.", err
        });
    }
}

然后我收到一条错误消息"Cast to [undefined] failed for value \"[{\"title\":\"Test set\",\"creator\":\"5a7898c403999200c4ee3ae5\",\"public\":\"true\"}]\" at path \"lociSets\""

创建LociSet模型没有问题,但是当我尝试保存场所模型时似乎打破了

1 个答案:

答案 0 :(得分:1)

由于lociSetsObjectId引用的数组,您可能需要尝试以下方法:

exports.createOne = async (req, res) => {

    const { title, public = true, loci = [] } = req.body
    const lociSet = new LociSet({
        title,
        public,
        loci,
        creator: req.user.id
    })

    try {

        const newLociSet = await lociSet.save()
        const place = await Place.findOneAndUpdate(
            { "title": req.params.title.toLowerCase() },
            { "$push": { "lociSets" : newLociSet._id } },
            { "new": true}
        )

        res.status(200).json(place)

    } catch (err) {
        res.status(500).send({
            message: "Some error occurred while creating the loci set.", err
        })
    }
}