2014-10-31 89 views
1

我有以下模式我已經寫了使用貓鼬:屬性與貓鼬模式的默認值不會持續

var querySchema = mongoose.Schema({ 
    quoteId: { type: String, default: '' }, 
    zipcode: { type: String, default: '' }, 
    email: { type: String, default: '' }, 
    type: {type: String, default: ''}, 
    isEmailChecked: { type: Boolean, default: true }, 
}); 

我僅提供3在querySchema性假設值的字段的結果當query對象的新實例堅持以默認值:

var query = {}; 
query.quoteId = "1414775421426"; 
query.email = "[email protected]"; 
query.type = "Foo"; 

但下面的文檔是我所看到的是結果集合中:

{ 
    "_id" : ObjectId("5453c27d0e4c3f2837071856"), 
    "email" : "[email protected]", 
    "type" : "Foo", 
    "quoteId" : "1414775421426", 
    "__v" : 0 
} 

query對象的新實例持久保存到MongoDB數據庫時,isEmailCheckedzipcode是否應該被分配默認值?

以下是我如何使用ExpressJS /的NodeJS持續查詢對象的實例:

app.post('/api/queries', function (req, res) { 
    QuoteQuery.create({ 
     quoteId: req.body.query.quoteId, 
     type: req.body.query.type, 
     zipcode: req.body.query.zipcode, 
     email: req.body.query.email, 
     isEmailChecked: req.body.query.isEmailChecked, 
    }, function (err, query) { 
     if (err) { 
      res.send(err); 
     } 
     res.json(query); 
    }); 
}); 

有人能幫助我明白爲什麼我得到的結果文檔在isEmailCheckedzipcode性質MongoDB的數據庫?

我在我的應用程序和MongoDB中使用NodeJS,AngularJS和ExpressJS。

回答

2

當您設置mongoose模型字段時,它不使用默認值。

至於解決方法,您可以使用下劃線延長貓鼬模型對象與它存在於你的query對象這樣的鍵:

_.extend(dbQueryObject, query); 

下面是完整的例子:

var mongoose = require('mongoose'); 

var querySchema = mongoose.Schema({ 
    quoteId: { type: String, default: '' }, 
    zipcode: { type: String, default: '' }, 
    email: { type: String, default: '' }, 
    type: {type: String, default: ''}, 
    isEmailChecked: { type: Boolean, default: true } 
}); 

var db = mongoose.createConnection('mongodb://localhost:27017/stackoverflow', 
    { server: { auto_reconnect: true } }, 
    function(err) { 
    var QuerySchema = db.model('test', querySchema); 

    var query = {}; 
    query.quoteId = "1414775421426"; 
    query.email = "[email protected]"; 
    query.type = "Foo"; 

    QuerySchema.create({ 
     quoteId: query.quoteId, 
     type: query.type, 
     zipcode: query.zipcode, 
     email: query.email, 
     isEmailChecked: query.isEmailChecked 
    }, function (err, query) { 
     process.exit(0); 
    }); 
    }); 

以下是在分貝:

{ 
    "_id" : ObjectId("5453ce3c9f7e0d13c52abf61"), 
    "type" : "Foo", 
    "email" : "[email protected]", 
    "quoteId" : "1414775421426", 
    "__v" : 0 
} 
+0

但是,如果我添加'created:{type:Date,default:Date.now}'作爲其他r屬性,並且不要顯式地將其設置在服務器端,它爲新創建的查詢實例的'created'屬性存儲默認值'Date.now'。 – skip 2014-10-31 19:02:23

+0

如果您在本地運行express,如果您更改了模式,請確保重新啓動 - 對於審閱此問題的其他人,上述'{type:Date,default:Date.now}'按預期工作並存儲默認值。 – user1534980 2014-12-14 18:30:03