Mongoose .save失败了

时间:2017-10-19 05:29:18

标签: javascript node.js mongodb mongoose

我在学习node.js& mongoDB& mongoose,可能是一周或者2.我现在遇到的问题是,我正在尝试通过mongoose .save()保存到数据库,但是它没有按预期工作。我正在看一个教程,它已经有3天了,所以应该是最新的,但我得到了奇怪的错误。

  

mpromise(mongoose的默认承诺库)已被弃用“测试[重复]时出错

我读过,在stackoverflow上我可以添加:

  

mongoose.Promise = require('bluebird');

它会工作,但代码甚至不会转到.save函数,也不会抛出错误。我不确定问题出在哪里。

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
let connectionString = 'mongodb://localhost:27017/mongo2';

mongoose.createConnection(connectionString, (err) => {
    if (err) {
        console.log(err);
        return;
    }

    let Student = mongoose.model('Student', {
        firstName: {type: String, required: true},
        lastName: {type: String, required: true},
        age: {type: Number},
        facultyNumber: {type: String, unique: true}
    });

    let me = new Student({
        firstName: 'Who',
        lastName: 'amI',
        age: 20,
        facultyNumber: '9374823104'
    });

    me.save().then((info) => {
        console.log(info);
    }).catch((error) => {
        console.log(error);
    });
});

编辑:结果是:创建了数据库,也创建了集合,但没有创建对象。一切都是空的。

1 个答案:

答案 0 :(得分:0)

很可能问题是您的模型没有附加架构。

const { Schema } = require('mongoose');
const StudentSchema = new Schema({
        firstName: {type: String, required: true},
        lastName: {type: String, required: true},
        age: {type: Number},
        facultyNumber: {type: String, unique: true}
    }};

let Student = mongoose.model('Student', StudentSchema);