Mongoose模式中具有默认值的属性不会保持不变

时间:2014-10-31 17:36:26

标签: angularjs node.js mongodb express mongoose

我有以下使用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数据库时,是否应该为zipcodequery分配默认值?

以下是我如何使用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数据库的结果文档中获得了isEmailCheckedzipcode属性?

我在我的应用程序中使用NodeJS,AngularJS和ExpressJS以及MongoDB。

1 个答案:

答案 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
}