Mongoose:在要保存的文档中不存在时,在必填字段中设置默认值

时间:2017-02-21 17:49:18

标签: node.js mongodb mongoose

我尝试在空字段中设置默认值,以便将文档保存在MongoDB中

就我而言,这是mongoose架构

@Before
    public void setUp() throws Exception {
        LogPack.logPacConfig(Constants.LOGGING_FILE);
        gtfri = "+RESP:GTFRI,380502,869606020101881,INCOFER-gv65,,10,1,1,0.0,0,888.1,-84.194560,9.955602,20170220074514,,,,,,0.0,,,,100,210100,,,,20170220074517,40A2$";
        weirdProtocol = "+RESP:GRI,380502,869606020101881,INCOFER-gv65,,10,1,1,0.0,0,888.1,-84.194560,9.955602,20170220074514,,,,,,0.0,,,,100,210100,,,,20170220074517,40A2$";
        factory = new LocomotiveFactory();
    }
    @Test
    public void GTFRICreationTester_shouldPass() throws TramaConProtolocoloDesconocido {
        assertTrue(factory.createLocomotive(gtfri, false, new Date()) instanceof LocomotiveGTFRI);
    }

    @Test(expected = TramaConProtolocoloDesconocido.class)
    public void GTFRICreationTester_shouldFail()  {
        try {
            factory.createLocomotive(weirdProtocol, false, new Date());
            fail("Expected an TramaConProtolocoloDesconocido");
        } catch (TramaConProtolocoloDesconocido e) {
            //assertSame("exception thrown as expected", "no se conoce el protocolo dado para la creacion de este factory", e.getMessage());;
        }
    }

这是要保存的文件:

var Distribution = new Schema({
    temporalCoverage: {
        startDate: {type: Date, default: Date.now},
        endDate: {type: Date, default: Date.now}
    },
    distributionText: String
});

在本文档中,空字段为endDate和startDate。该文档以空值保存在mongoDB中。

"distribution": {
    "temporalCoverage": {
      "endDate": "",
      "startDate": ""
    },
    "distributionText": "test"
  }

我想保存默认值,而不是null

如果在模式中放置了所需的字段,"distribution": { "temporalCoverage": { "endDate": null, "startDate": null }, "distributionText": "test" } 我得到了错误验证,并且文档没有保存。

1 个答案:

答案 0 :(得分:6)

您需要setDefaultsOnInsert选项

var schema = new Schema({
  title: String,
  genre: {type: String, default: 'Action'}
});

var Movie = db.model('Movie', schema);

var query = {};
var update = {title: 'The Terminator'};
var options = {
  // Create a document if one isn't found. Required
  // for `setDefaultsOnInsert`
  upsert: true,
  setDefaultsOnInsert: true
};

Movie.
  findOneAndUpdate(query, update, options, function (error, doc) {
    assert.ifError(error);
    assert.equal(doc.title, 'The Terminator');
    assert.equal(doc.genre, 'Action');
  });

请参阅http://mongoosejs.com/docs/defaults.html