Dynamic mongoose schema parsing with ExpressJS

Report
Question

Please briefly explain why you feel this question should be reported .

Report Cancel

I am working on a ExpressJS and MongoDB project that involves parsing dynamic mongoose schema. The way I set up the dynamic schema is and parse it :

Step-1

//Creating a mongoose schema
var userSchema = mongoose.Schema({
measurements : [
        mongoose.Schema({
        time: String
    })
]});

Step-2

//Creating a mongoose model for the schema
var User = mongoose.model('User', userSchema);

var user = new User();
user.measurements = [{time:req.body.time}]

//save the info
user.save(function(err) {
if (err)
 res.send(err);
 res.send({message: "User Info created"});
});
});

Expected result :

A example with JSON validator to explain my goal clearly:

enter image description here
But the issue is my code posts data in the following way to the mongo database :

enter image description here

I was wondering if it is possible to post new array object with time attribute instead of having the comma separated values.
Any thoughts and suggestions on this would be appreciated.

Thanks

solved 0
1 Answer 8 views 0

Answer ( 1 )

    0
    January 11, 2017 at 7:30 pm

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    You are doing it the wrong way.

    Try this:

    var user = new User();
    user.measurements.push({time:req.body.time});
    
    //save the info
    user.save(function(err) {
    if (err)
     res.send(err);
     res.send({message: "User Info created"});
    });
    });
    
    Best answer

Leave an answer

Browse

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>