1

考虑一下,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*/});

现在我的问题是:我为什么要创建一个json_obj。当我手中已经有一个模式对象时,它已经具有所有字段(field1,field2)。如果我只想为这些字段提供值,为什么要通过再次写入所有字段名称来创建 json?

如果我有n个字段,这将成为再次写入所有字段的开销。有什么办法可以避免这种开销?

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

4

3 回答 3

3

您在寻找什么样的 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();

在网络应用程序中,这变成了类似

app.post('/things', function(req, res) {
  var thing = new Thing(req.body.thing);
  thing.save(function() { ... });
});
于 2013-01-17T07:36:08.693 回答
1

以下是我迄今为止找到的最佳解决方案

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); });
于 2013-01-17T08:09:46.847 回答
1

如果您使用的是 ES6,则扩展运算符可能会派上用场。考虑到您已经定义了猫鼬模型,并且您正在从 req.body 获取字段值。您可以通过简单地像这样编写它来为该模型创建一个新对象:

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
})
于 2016-12-08T09:33:52.333 回答