使用mongoose创建mongodb时的验证错误

时间:2017-02-16 22:05:57

标签: node.js mongodb mongoose

我很难使用猫鼬保存到mongodb。这是我得到的错误

应用程序抛出了未捕获的异常并被终止: ValidationError:pageModel验证失败

我的代码

//page.js   
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var pageShema = new Schema({
    pageId: {
        type: String,
        required: true
    },
    logo: {
        type: String
    },
    subline: {
        type: String
    },
    header: {
        type: String
    },
    created_on: {
        type: Date,
        default: Date.now
    },
    offense:{
       type: Schema.Types.Mixed
    },
    deffense:{
        type: Schema.Types.Mixed
    }
});

var pageModel = mongoose.model('pageModel', pageShema);

module.exports = pageModel;

app.js

var mongoose = require('mongoose');
var dbURL = config.dbURL;
mongoose.connect(dbURL);
var pagedb = require('./models/page');

var page = new pagedb( {
    pageId: 'test',
    logo:'test logo',
    subline: 'test subline', 
    header: 'test header',
    created_on: Date.now,
    offense: {},
    deffense: {}
});


page.save(function (err, page) {
    if (err) {
        console.log('error!');
        throw err;
    };
    console.log('page is created!');
});

1 个答案:

答案 0 :(得分:0)

由于日期字段而失败。使用new Date()代替Date.now

var mongoose = require('mongoose');
var dbURL = config.dbURL;
mongoose.connect(dbURL);
var pagedb = require('./models/page');

var page = new pagedb( {
    pageId: 'test',
    logo:'test logo',
    subline: 'test subline', 
    header: 'test header',
    created_on: new Date(),
    offense: {},
    deffense: {}
});


page.save(function (err, page) {
    if (err) {
        console.log('error!');
        throw err;
    };
    console.log('page is created!');
});