How to normalize mongoose scema

1.4k Views Asked by At

i am getting an output as object with arrays of object inside. i am totally confused with mapping this i am getting error while doing this so i need to convert it to normalizr. i dont know how to do it. my shema is given below

code:-

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
require('mongoose-double')(mongoose);
var Schema = mongoose.Schema;
var SchemaTypes = mongoose.Schema.Types;
var TestSchema = new Schema(
{
  name:{type: String, required: true},
  type: {type: Boolean},
  artists: {type: Array},
  total_count: {type: String},
  active: {type: Boolean}  
}
);

module.exports = mongoose.model('Test', TestSchema);

and i am retrieving data like:-

code:-

router.post('/getoneartist',function(req, res){
    Test.findOne({_id : req.body.id}).populate({ path: 'artists', model: 'Artist' }).exec()
    .then(function(test){
        res.send(test)
    })
})

now i am getting data like this :

{
id:123,
name:new,
type:true,
artists:[
{id:123,name:artist1}
{id:126,name:artist2}
],
total_count:25,
active:true
}

while maping data i am getting undefined error.so i need to convert it to normalizr format.is there any way to convert it to another format.

thanks in advance

1

There are 1 best solutions below

0
On

Look like your JSON is Incorrect

Working Example :

        const {map} = require('lodash');
        let test =  {id:123, name:"new", type : true, artists: [{id:123,name:"artist1"}, {id:126,name:"artist2"} ],total_count:25,active:true}
        let name = map(test.artists,'name'); //lodash

        let name_native = test.artists.map(item=>{ return item.name});//native
        console.log(name);
        console.log(name_native)

In react You can use Map by

import { map} from 'lodash';

let name = map(test.artists,'name'); //from lodash
let name_native = test.artists.map(item=>{ return item.name}); //native