猫鼬 .save 失败 [英] Mongoose .save fails

查看:57
本文介绍了猫鼬 .save 失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I learning node.js & mongoDB & mongoose, from maybe a week or 2. The problem I have right now is, I'm trying to save to db via mongoose .save(), but it doesn't work as expected. I'm watching a tutorial, and it's 3 days old, so should be up to date, but I'm getting strange error.

mpromise(猫鼬的默认承诺库)在测试时被弃用"错误[重复]

mpromise (mongoose's default promise library) is deprecated" error when testing [duplicate]

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

I read, here on stackoverflow that I can just add:

mongoose.Promise = require('bluebird');

mongoose.Promise = require('bluebird');

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

It will work, but the code doesn't even go to the .save function, and don't trow an error. I'm not sure where the problem is.

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);
    });
});

结果是:创建数据库,创建集合,但不是对象.一切都是空的.

The result is: Getting the DB created, the collection too, but not the object. Everything is empty.

推荐答案

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

Very likely the problem is that your model does not have a schema attached.

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);

这篇关于猫鼬 .save 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆