猫鼬模式中的对象数组问题

时间:2019-03-31 14:36:41

标签: mongodb express mongoose

我对基于node express和mongodb和mongoose的rest api有问题,我认为我对对象嵌套数组的mongoose模式有问题

我尝试过控制台日志req.body并且有数据,但是当我使用猫鼬的新架构时,就会有空数组

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

const TranslationSchema = new Schema({
    name: {
        type: String,
        required:true
        },
    description: {
        type: String
    },
    laguage_code: {
        type: String,
        required:true
    },
})

const ImagesSchema = new Schema({
    name:{
        type: String
    },
    file_id: {
        type: String
    }
})
const RecipeSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    translations:[TranslationSchema],
    date: {
        type: Date,
        default: Date.now
    },
    images:[ImagesSchema]
})
module.exports = Recipe = mongoose.model("recipes", RecipeSchema);

和api

router.post(
    '/',
    passport.authenticate('jwt', { session:false }),
    (req,res) => {
        const newRecipe = new Recipe({
            user: req.user.id,
            translations:req.body.translations,
            images:req.body.images
        })
        console.log(req.body)
        console.log(newRecipe)
        // newRecipe.save().then(recipe => res.json(recipe))
    }
)

在console.log需要的机身上

[Object: null prototype] {
  images: '[{name:\'test\', file_id:\'asd\'}]',
  translations: '[{name:\'asd\', laguage_code:\'pl\'}]' }

但在console.log(newRecipe)

{ _id: 5ca0cc632314cd4368bf42dd,
  user: 5c569f603e811118c83c80d1,
  translations: [],
  date: 2019-03-31T14:19:15.788Z,
  images: [] }

我做错了什么?

1 个答案:

答案 0 :(得分:0)

Recipe模型中,您也将translationsimages定义为猫鼬模型。因此,请尝试导出这些模型并进行构建。例如:

const translations = new Translation(req.body.translations);
const images = new Image(req.body.images);

然后尝试以这种方式创建模型:

const newRecipe = new Recipe({
    user: req.user.id,
    translations:translations,
    images:images
})

我希望我给你一个想法,如何尝试找到您的解决方案。