Home > Enterprise >  Creating 5 items and updating the array in mongodb (Continue Discussion from my previous question)
Creating 5 items and updating the array in mongodb (Continue Discussion from my previous question)

Time:03-20

I did change something new with the database..Since I have 5 mongodb item..here is the code This is for my main-model.js

const mongoose = require('mongoose')

const Schema = mongoose.Schema

const mainSchema = new Schema({
    likes:{
        type:Number,
        max:100000
    },
    people:[{
        key:{type:String},
        name:{type:String}
    }]
},{
    timestamps:true
})

const MAIN = mongoose.model('liker-model',mainSchema)

MAIN.insertMany([
    {"_id":mongoose.Types.ObjectId(1),likes:0,people:[]},
    {"_id":mongoose.Types.ObjectId(2),likes:0,people:[]},
    {"_id":mongoose.Types.ObjectId(3),likes:0,people:[]},
    {"_id":mongoose.Types.ObjectId(4),likes:0,people:[]},
    {"_id":mongoose.Types.ObjectId(5),likes:0,people:[]},
])

module.exports = MAIN

Now I will pass liker.js which will be the code

const router = require('express').Router()
let Main = require('../models/main-model')

router.route('/').get((req,res) => {
    Main.find()
        .then(likes => res.json(likes))
        .catch(err => console.log(err))
})

router.route('/item/:id').post((req,res) => {

    const id = req.params.id
    
    console.log(id)

    if (!id) return res.status(400).json({ message: "missing id" });

    const { likes, people } = req.body;

    Main
        .updateOne(
        { _id: id },
        {
            $addToSet: { people: { $each: people } },
            $set: {
                likes,
            },
        },
        )
        .then((likes) => res.json({ message: "New User Added" }))
        .catch((err) => res.status(400).json("Error :"   err));

})  

module.exports = router

Based on what you discuss this enter image description here What my point here is that since I have 5 photo items in my frontend that means I need 5 items in my database which you will see in my main-model.js. Now since I have the idea of how I will push my items in my array for each item that I want to push. In the code that you mention in my post

router.route('/item/1').post((req,res) => {

    const { likes, people } = req.body

    Main.updateOne({likes}, {$addToSet: { people: {$each: people} } } )
    .then(likes => res.json('New User Added'))
    .catch(err => res.status(400).json('Error :'   err))

})  

but since I need the id as you mention before...

router.route("/item/:id").post((req, res) => {
  const id = req.params.id;
  if (!id) return res.status(400).json({ message: "missing id" });
  const { likes, people } = req.body;

  const model = mongoose.model("collection_name", mainSchema);

  model
    .updateOne(
      { _id: id },
      {
        $addToSet: { people: { $each: people } },
        $set: {
          likes,
        },
      },
    )
    .then((likes) => res.json({ message: "New User Added" }))
    .catch((err) => res.status(400).json("Error :"   err));
});

but in my insertMany() it creates its own ID so that I have to pass it in my frontend

      axios.get('http://localhost:7171/likes')
        .then(listid => setlistid(list.data))
        .catch(err => console.log(err))

something like this and pass it back to my backend/database

axios.post('http://localhost:7171/likes/item/listid[0]._id',{ people:{name:name,key:key }})
          axios.post('http://localhost:7171/likes/item/listid[1]._id',{ people:{name:name,key:key } })
          axios.post('http://localhost:7171/likes/item/listid[2]._id',{ people:{name:name,key:key } })
          axios.post('http://localhost:7171/likes/item/listid[3]._id',{ people:{name:name,key:key } })
          axios.post('http://localhost:7171/likes/item/listid[4]._id',{ people:{name:name,key:key } })

I have already get it..but do you have any idea how can I not recreate again another 5 items in my main-model.js whenever I tried to rerun my server.js???

ugh this is my longest discussion lol..

CodePudding user response:

Firstly, mongodb doesn't store id as integer ( like 1,2,3,4,5 ) but store as ObjectId

ref: https://mongoosejs.com/docs/guide.html#_id


Secondly, if you want insert multiple default value for collection liker-model. The way you are using is wrong, because code id with mongoose.Types.ObjectId(1) will generate a new once every time you start your nodejs backend server. You should do something like


const defaultIdLikerModel = [
  "00000001a24dfc9b806e607f",
  "00000001a24dfc9b806e607d",
  "6235f2fea24dfc9b806e6080",
  "6235f306a24dfc9b806e6081",
  "6235f30aa24dfc9b806e6082",
]; // generate default id to query insert only not exist

const queries = []; // push multiple query insert if not exist

defaultIdLikerModel.forEach((likerId) => {
  queries.push(
    MAIN.findOneAndUpdate(
      { _id: likerId },
      {
        $setOnInsert: {
          likes: 0,
          people: [],
        },
      },
      {
        upsert: true,
      },
    ),
  );
});

await Promise.all(queries); // execute all queries

Thirdly, in your route /item/:id. If you require main-model.js as you was declared a model with const MAIN = mongoose.model('liker-model',mainSchema), you doesn't need to re-declare with const model = mongoose.model("collection_name", mainSchema);. Just use something like this

const model = require('./main-model')

model.updateOne(
        { _id: id },
        {
            $addToSet: { people: { $each: people } },
            $set: {
                likes,
            },
        },
        )
        .then((likes) => res.json({ message: "New User Added" }))
        .catch((err) => res.status(400).json("Error :"   err));
  • Related