'Add key value pair data

I have a schema in Mongoose that looks like this:

const SocketDetailsUserSchema = new mongoose.Schema({
    userId: String, 
    socketValue:  [{
       id: String,
       data : String     
     }], 
    isDeleted: Boolean,
    dateCreated: Date,
    updateAt: Date
});

I want to insert data of socketValue in key value pair in array format. Which should look like ,

{
    "_id" : ObjectId("5a12809c7f7afb1e3626857f"),
    "userId" : "59eee19696fe6560cd54a081",
    "socketValue" :  [{"id":"5a05855b10600e4aa5b3a48e" , "value" : "123" }],[{"id":"5a0ae037a90746c249b6c1f7" , "value" : "456" }],
    "isDeleted" : false 
    "__v" : 0
}

This is the mongoose data format.

How can i insert data in mongoose like this ? I am also confused that how should i post data from postman to insert data in this ?



Solution 1:[1]

I think your current structure is good just add _id: false to avoid to add auto generated _id in socketValue. like

socketValue:  [{
   id: String,
   data : String,
   _id: false
 }],

for this structure data will store like:

"socketValue" :  [{"id":"5a05855b10600e4aa5b3a48e" , "value" : "123" },{"id":"5a0ae037a90746c249b6c1f7" , "value" : "456" }]"

then you can easily update or add new socketValue. I think this [{..},{..},{..}] is the better structure instead of [[{..}][{..}]] this structure.

and for this structure postman request body should contain like.

{
    "userId" : "59eee19696fe6560cd54a081",
    "socketValue" :  [{"id":"5a05855b10600e4aa5b3a48e" , "value" : "123" },{"id":"5a0ae037a90746c249b6c1f7" , "value" : "456" }]",
    "isDeleted" : false 
}

and in your server side code just use like

var newSocket = new Socket(req.body); // assume your model name is Socket
newSocket.save();

Solution 2:[2]

Your postman input data should be raw json format

{
    "userId" : "59eee19696fe6560cd54a081",
    "socketValue" :  [{"id":"5a05855b10600e4aa5b3a48e" , "value" : "123" },{"id":"5a0ae037a90746c249b6c1f7" , "value" : "456" }]",
    "isDeleted" : false 
} 

Your server code

var insertDoc = new collectionname(details);
inserDoc.save(function (err) {
    if (err) {
        //callback err
    } else {
        //callback result
    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shaishab Roy
Solution 2 Sai Reddy