简体   繁体   中英

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

At this moment I try to find the query which works in this case, but then want to update the object. So I want to check if review object exist and if not then create that key name first and then push that object into an array. Else push into that in existing object of array.

Default object looks like (without review 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); } });

  • check if reviews field is not exists then initialise it to blank array
  • push object to reviews
  • save() to save main document
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);
  }
});

Second option using updateOne() :

It does not require to find, check and save operations if you use update methods,

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);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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