用猫鼬保存嵌套对象(数组),导致在mongodb中出现空对象

黑色54

问题是如此基本:我想用mongoose将嵌套对象保存在mongodb中,但是当我保存它们时,嵌套对象为空

我已经尝试过其他解决方案,但不能解决我的问题。推送对象,填充等。但这仅在您要求该信息不保存时起作用。所以我在这里。

模型


const mongoose = require('mongoose')
let Schema = mongoose.Schema
const respuestaSchema = new Schema({
    resp:{type:String},
    value:{type:String}
},{ _id : false })

const preguntasSchema = new Schema({
    pregunta:{type:String},
    tipo:{type:String},
    respuesta:[respuestaSchema]
},{ _id : false })

let testSchema = Schema({
    _id:{type:Schema.ObjectId, auto:true},
    name: {type:String},
    dName:{type:String},
    categoria:{type:[Schema.ObjectId],ref:'categoria'},
    preguntas:[preguntasSchema]

},{versionKey:false})

module.exports = mongoose.model('test',testSchema)

保存测试:

const Test = require('../models/test')

exports.newTest = function(req,res){
    let param = req.body
    let nTest = new Test()
    nTest.name = param.name
    nTest.dName = param.dName
    nTest.categoria = param.categoria
    nTest.pregunta = param.pregunta
    nTest.tipo = param.tipo
    nTest.resp = param.resp
    nTest.value = param.value
    nTest.preguntas.push(nTest)
    nTest.save().then(
        testSaved=>{
            res.status(200).send({accion:'newTest',mensaje:'Test creado correctamente'})
        }
    ).catch(err=>{res.status(500).send({accion:'newTest',mensaje:'Error en creacion de test ' +err})})
}

我确实nTest.preguntas.push(nTest)保存了preguntas并保存了它,但是该对象中的信息没有出现,只出现了object [],因为preguntas内部还有另一个对象。

我希望在Compass或Robo3T上看到我传递的所有信息,但我只会看到不是嵌套对象的信息,而嵌套对象的标题却是空的。如果您需要db中问题的img捕获,我可以发送。希望您能为我提供此信息。

伊拉里奥·哈卢什卡

我已根据您声明的方案编辑了您的代码,请尝试:

exports.newTest = ({ body: param }, res) => {
  const nTest = new Test();
  nTest.name = param.name;
  nTest.dName = param.dName;
  nTest.categoria = param.categoria;
  nTest.preguntas = [
    {
      pregunta: param.pregunta,
      tipo: param.tipo,
      respuesta: [
        {
          resp: param.resp,
          value: param.value,
        },
      ],
    },
  ];
  // your saving func
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章