【问题标题】:Nodejs/MongoDB: Push dynamically created object into arrayNodejs/MongoDB:将动态创建的对象推送到数组中
【发布时间】:2020-01-08 16:47:19
【问题描述】:

我想使用 mongodb 和 nodejs 将对象推送到数组中。 我的词架构是:

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

const wordSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  date: {
    type: Date,
    default: Date.now
  },
  ugrWordCyr: {
    type: String,
    required: true
  },
  ugrWordArb: {
    type: String
  },
  rusTranslation: {
    type: String,
    required: true
  },
  examples: [
    {
      exCyr: { type: String },
      trRus: { type: String },
      exLat: { type: String },
      trEng: { type: String },
      exArab: { type: String }
    }
  ],
  origin: {
    type: String
  },
  sphere: {
    type: String
  },
  see: {
    type: Boolean,
    default: false
  },
  lexis: {
    type: String
  },
  grammar: {
    type: String
  },
  partOfSpeech: {
    type: String
  },
  style: {
    type: String
  }
});

module.exports = Word = mongoose.model("words", wordSchema);

如您所见,架构中有示例数组。它需要充满动态创建的对象。所以用我的话 api 我正在做这件事,但它不起作用。

// @route  POST api/words
// @desc   Add words to profile
// @access Private
router.post(
  '/',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Word.find({}).then(word => {
      if (
        word.filter(
          wrd =>
            wrd.ugrWordCyr.toString().toLowerCase() ===
            req.body.ugrWordCyr.toLowerCase()
        ).length !== 0
      ) {
        return res
          .status(404)
          .json({ wordalreadyexists: 'Word already exists' });
      } else {
        const newWord = new Word({
          user: req.user.id,
          ugrWordCyr: req.body.ugrWordCyr,
          ugrWordArb: req.body.ugrWordArb,
          rusTranslation: req.body.rusTranslation,
          origin: req.body.origin,
          sphere: req.body.sphere,
          lexis: req.body.lexis,
          grammar: req.body.grammar,
          partOfSpeech: req.body.partOfSpeech,
          style: req.body.style
        });
        // Social
        newWord.examples = [];
        /* if (req.body.exCyr) newWord.examples.exCyr = req.body.exCyr;
        if (req.body.trRus) newWord.examples.trRus = req.body.trRus;
        if (req.body.exLat) newWord.examples.exLat = req.body.exLat;
        if (req.body.trEng) newWord.examples.trEng = req.body.trEng;
        if (req.body.exArab) newWord.examples.exArab = req.body.exArab; */
        newWord.examples.push({
          exArab:req.body.exArab,
          trRus:req.body.trRus,
          exLat:req.body.exLat,
          trEng:req.body.trEng,
          exArab:req.body.exArab
        })
        newWord.save().then(word => {
          //now update user model
          User.findOne({ _id: req.user.id })
            .then(foundUser => {
              foundUser.score = foundUser.score + 150;
              foundUser
                .save()
                .then(savedUser => {
                  res.json({ word, savedUser });
                })
                .catch(err => {
                  return res.status(400).json({ error: 'could not add score' });
                });
            })
            .catch(err => {
              return res.status(400).json({ error: 'could not find user' });
            });
        });
      }
    });
  }
);

我做错了什么?前端没问题!

【问题讨论】:

  • 您能否分享任何错误消息,或者究竟是什么不起作用?
  • 没有特别的错误,当我检查我的 mongolab 云时,示例数组是空的。
  • Word.find({}) 返回什么?
  • 返回所有存在的单词。

标签: node.js reactjs mongodb


【解决方案1】:

我认为这是因为您试图推送到 Model 实例上尚不存在的数组。

在创建 Model 实例时将空数组添加到它或保存模型两次。创建空数组后,然后推入它。

试试这个:

const newWord = new Word({
          user: req.user.id,
          ugrWordCyr: req.body.ugrWordCyr,
          ugrWordArb: req.body.ugrWordArb,
          rusTranslation: req.body.rusTranslation,
          origin: req.body.origin,
          sphere: req.body.sphere,
          lexis: req.body.lexis,
          grammar: req.body.grammar,
          partOfSpeech: req.body.partOfSpeech,
          style: req.body.style,
          examples: []; //add it here
        });

或者这个:

        newWord.examples = [];

        newWord.save().then(word => {
        // now push into the added array and then save again
        newWord.examples.push({
          exArab:req.body.exArab,
          trRus:req.body.trRus,
          exLat:req.body.exLat,
          trEng:req.body.trEng,
          exArab:req.body.exArab
        })

【讨论】:

  • 嗨@Travis James,我已经尝试过你的解决方案,但示例数组仍然是空的。不知道为什么我尝试了你的两个建议。
【解决方案2】:

这是一个正确的解决方案。无需将任何东西推入数组。

const newWord = new Word({
              user: req.user.id,
              ugrWordCyr: req.body.ugrWordCyr,
              ugrWordArb: req.body.ugrWordArb,
              rusTranslation: req.body.rusTranslation,
              origin: req.body.origin,
              sphere: req.body.sphere,
              lexis: req.body.lexis,
              grammar: req.body.grammar,
              partOfSpeech: req.body.partOfSpeech,
              style: req.body.style,
              examples: req.body.examples
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2020-10-24
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多