Reputation: 21639
Consider, Mongoose schema:
var schema_obj = new Schema({
field1: String,
field2: String, .........
});
JSON document, like:
var json_obj = {
field1: 'value',
field2 : 'val2',
............
};
For saving I call method, like
var Model_obj = mongoose.model('model_name', schema_object);
var document_obj = new Model_obj(json_obj);
document_obj.save(function(err,data){/*some logic after save*/});
Now my question is: Why should I create a json_obj. When I already have a schema object in my hand, which already has all the fields (field1, field2). If I just want to give values for those fields why should I create json by writing all the field name again?
If I have n number of fields this becomes a overhead to write all fields again. Is there any way to avoid this overhead?
Something like I get a empty JSON object out of my defined mongoose schema, then just proceed by assigning only values?
Upvotes: 1
Views: 4681
Reputation: 609
If you are using ES6, the spread operator might come in handy for this purpose. considering that you have your mongoose model defined and you are getting your field values from req.body. you can create a new object for that model by simply writing it like this:
const Thing = mongoose.model('collection_name', sch_obj);
const json_obj = new Thing({ ...req.body });
json_obj.save()
.then(savedThing => {
//DO things with your saved object.
})
.catch(error => {
//Handle error in saving the object
})
Upvotes: 1
Reputation: 21639
var sch_obj = new mongoose.Schema({
"_id ": String,
"field1": String,
"field2": String
}, { collection: 'collection_name'});
var Mod_obj = mongoose.model('collection_name', sch_obj);
var json_obj = new Mod_obj({
"_id ": 'Strin', /*This is the only field which cannot be assigned later*/
});
//json_obj._id = 'some value'; /*THIS CANNOT BE DONE*/
json_obj.field1 = 'value1';
json_obj.field2 = 'value2';
json_obj.save(function (err, data) { console.log(data); });
Upvotes: 1
Reputation: 159125
What kind of API are you looking for? You can set properties on a model instance and save
it. But I'm not sure if I understand why
var thing = new Thing();
thing.name = "The Name";
thing.priceInCents = 1999;
thing.numAvailable = 10;
thing.save();
is easier than
var thing = new Thing({name: 'The name', priceInCents: 1999, numAvailable: 10});
thing.save();
In a web app, this becomes something like
app.post('/things', function(req, res) {
var thing = new Thing(req.body.thing);
thing.save(function() { ... });
});
Upvotes: 3