为什么我应该创build一个json来保存来自Mongoose + MongoDB + Node.JS的文档?

考虑一下,Mongoose模式:

var schema_obj = new Schema({ field1: String, field2: String, ......... }); 

JSON文件,如:

 var json_obj = { field1: 'value', field2 : 'val2', ............ }; 

为了节省我的通话方式,就像

 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*/}); 

现在我的问题是:为什么我应该创build一个json_obj 。 当我已经有一个模式对象在我手中,已经有所有的字段(field1,field2)。 如果我只是想给这些字段的值,为什么我应该通过再次写入所有的字段名称来创buildjson?

如果我有n个字段,则会重新编写所有字段。 有什么办法可以避免这种开销?

就像我从我定义的mongoose模式中得到一个空的JSON对象,然后只通过分配值?

你在找什么样的API? 您可以在模型实例上设置属性并save 。 但是我不确定我是否明白为什么

 var thing = new Thing(); thing.name = "The Name"; thing.priceInCents = 1999; thing.numAvailable = 10; thing.save(); 

比…容易

 var thing = new Thing({name: 'The name', priceInCents: 1999, numAvailable: 10}); thing.save(); 

在一个networking应用程序,这成为像

 app.post('/things', function(req, res) { var thing = new Thing(req.body.thing); thing.save(function() { ... }); }); 

以下是迄今为止我find的最佳解决scheme

 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); }); 

如果您使用的是ES6,则传播运算符可能会派上用场。 考虑到你有你的mongoose模型定义,你从req.body得到你的字段值。 你可以创build一个新的对象为该模型只需写这样的:

 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 })