繁体   English   中英

如何添加新的 object 或推入数组 Mongodb Compass NodeJS Express(更新不是功能)?

[英]How do I add new object or push into array Mongodb Compass NodeJS Express (update is not a function)?

此时我尝试查找在这种情况下有效的查询,但随后想更新 object。 所以我想检查审查 object 是否存在,如果不存在,则首先创建该键名,然后将该 object 推送到数组中。 否则推入现有的 object 阵列中。

默认 object 看起来像(没有评论对象):

在此处输入图像描述

 const mongoose = require('mongoose'); const musicSchema = mongoose.Schema({ id: { type: Number, required: true }, artist: { type: String, required: true }, title: { type: String, required: true }, release_year: { type: Number, required: true }, genre_id: { type: Number, required: true }, image_url: { type: String, required: true }, reviews: [{ id: { type: Number, required: true }, locale: { type: String, required: true }, rating: { type: Number, required: true }, comment: { type: String, required: true } }] }); const Music = mongoose.model("Music", musicSchema); // now we have to create our model console.log; module.exports = Music; // export our created model

 app.post('/addReview/:id', async (req, res) => { let idNumber = parseInt(req.params.id); // 501437 let reviewObject = req.body; // {id: "501437", locale: "nl", rating: 3, text: "helello"} try { const music = client.db('database').collection('music'); const query = { id: idNumber }; const musicSong = await music.findOne(query); await musicSong.update({ $push: { reviews: reviewObject } }); // error comes from here } catch (err) { console.log(err); } });

  • 检查reviews字段是否不存在,然后将其初始化为空白数组
  • 将 object 推送到reviews
  • save()保存主文档
app.post('/addReview/:id', async (req, res) => {
  let idNumber = parseInt(req.params.id);  // 501437
  let reviewObject = req.body; // {id: "501437", locale: "nl", rating: 3, text: "helello"}
  try {
    const music = client.db('database').collection('music');
    const query = { id: idNumber };
    let musicSong = await music.findOne(query);
    if (!Array.isArray(musicSong.reviews)) {
      musicSong.reviews = [];
    }
    musicSong.reviews.push(reviewObject);
    music.save();
  } catch (err) {
    console.log(err);
  }
});

使用updateOne()的第二个选项:

如果您使用更新方法,则不需要查找、检查和保存操作,

app.post('/addReview/:id', async (req, res) => {
  const query = { id: parseInt(req.params.id) };
  let reviewObject = req.body;
  try {
    const music = client.db('database').collection('music');
    await music.updateOne(query, { $push: { reviews: reviewObject } });
  } catch (err) {
    console.log(err);
  }
});

暂无
暂无

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

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