繁体   English   中英

将子文档推送到父文档数组。 只有 Object_ID 被推送

[英]Pushing subdocument to parent document array. Only Object_ID gets pushed

我对 mongoose 很陌生。 我在这里找到了可以回答的类似问题,但它们与我的问题不太相似/我不知道它有什么相似之处。

我正在尝试将子文档推送到父文档上的数组中。 目前我这样做:上传音板

const multer = require('multer')
const FILE_PATH  = 'uploads'
const passport = require('passport')
const strategy = require('../strategies/strategy')
const upload = multer({
  dest: `${FILE_PATH}/`
})
const { Soundboard } = require('../models/soundboard')
const express = require('express')
const router = express.Router()

passport.use(strategy.jwtStrategy)

router.post('/', passport.authenticate('jwt', { session: false }), async (req, res) => {
  try {
    //console.log(req.body.name)
    req.user.soundboards.push({
      name: req.body.name,
    })
    //console.log(req.user.soundboards)
    await req.user.save()
    res.send('Success!')
  } catch (err) {
    res.status(500).send(err)
  }
})

module.exports = router

这实际上将子文档推送到数组,但它只添加了 Object.ID,而不是我请求的名称。 架构看起来像这样:

用户

const User = mongoose.model('User', new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  email: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 1024
  },
  soundboards: [SoundboardSchema]
}))

音板


const Soundboard = new Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  sounds: {
    type: [SoundSchema],
    required: false
  }
})

声音


const Sound =  new Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  path: {
    type: String,
    required: true
  }
})

有人看到答案吗? 提前致谢!

这就是你应该使用它的方式:

router.post('/', passport.authenticate('jwt', { session: false }), async (req, res) => {

    try {

        let newSoundboards = {
            name: req.body.name,
        }

//I don't see you loading your model somewhere with the connection
//So I used yourDB as an example.

        await new yourDB(newSoundboards).save()
        res.send('Success!')
    } catch (err) {
        res.status(500).send(err)
    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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