我有以下使用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 },
});
我只为querySchema
中的3个属性提供值,假设当query
对象的新实例持久存在时,字段的结果将采用默认值:
var query = {};
query.quoteId = "1414775421426";
query.email = "myself@somewhere.com";
query.type = "Foo";
但是下面的文件是我在集合中看到的结果:
{
"_id" : ObjectId("5453c27d0e4c3f2837071856"),
"email" : "myself@somewhere.com",
"type" : "Foo",
"quoteId" : "1414775421426",
"__v" : 0
}
当isEmailChecked
对象的新实例持久保存到MongoDB数据库时,是否应该为zipcode
和query
分配默认值?
以下是我如何使用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);
});
});
有人可以帮我理解为什么我在MongoDB数据库的结果文档中获得了isEmailChecked
和zipcode
属性?
我在我的应用程序中使用NodeJS,AngularJS和ExpressJS以及MongoDB。
答案 0 :(得分:2)
设置mongoose模型字段时,不使用默认值。
作为解决方法,您可以使用下划线来扩展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 = "myself@somewhere.com";
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);
});
});
以下是db中的内容:
{
"_id" : ObjectId("5453ce3c9f7e0d13c52abf61"),
"type" : "Foo",
"email" : "myself@somewhere.com",
"quoteId" : "1414775421426",
"__v" : 0
}