Insert all upcoming data in one property in MongoDb using Mongoose

Viewed 33

My Upcoming data is :

{
  id: 123
  contact: 4591112365
  address: Block C New York 
  firstname: John
  lastname: Wick

}

Now on inserting data using Mongoose on Mongodb, I want my data to be inserted as this:

{
id: 123
contact: 4591112365
information:{
    address: Block C New York 
    firstname: John
    lastname: Wick
   }
}

I am using NodeJs and don't want to programmatically map the data, I want when I insert data in the above format it will automatically map to below one, I Think Using mongoose schema and virtual function or virtual ID I can do that but I am not sure about how to do that.

1 Answers

//make model

         const mongoose = require("mongoose");

        const infoSchema = new mongoose.Schema({
         contact:{
          type:Number
        }
           id:{
              type:Number    
            },      
            information: {
              address: {
                type:String,
              },
              firstName: {
                type:String,
              },
              lastName: {
                type:String,
              },
            },
            })
            
            module.exports = mongoose.model("User", infoSchema);

// make new user by importing that model into this js file
const User= require('/path/to/userModel')
          const user = new User({
            id:req.body.id,
            contact:req.body.contact,
            "information.address":req.body.address
            "information.firstName":req.body.firstName
            "information.lastName":req.body.lastName
        });    
        savedUser=user.save()

Related