草庐IT

node.js - mongoose.save() 有两种类型的行为

coder 2023-11-05 原文

我正在学习 mongoose,我正在发出一个简单的发布请求以将用户添加到我的 mongolab 测试数据库中。我使用的是基本用户模式,但是当我运行 save() 方法时,我有时会得到一个

Unhandled promise rejection (rejection id: 1): Error: data and salt arguments required

有时什么也没有发生,应用程序什么也不做。我正在使用 Postman 来测试发布请求。

编辑:正如 mikey 所建议的,我删除了 Resolve 和 Reject 回调并处理了 .save() 回调中的所有内容,但现在我收到以下错误:

(node:10964) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http:// mongoosejs.com/docs/promises.html

var express = require('express');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require("body-parser");

var mPromise = require("mpromise");

var User = require('./models/user');

var app = express();


mongoose.connect('mongodb://root2:1234@ds161742.mlab.com:61742/ecommerce', function (err) {
    if (err) console.log(err);

    console.log("Connected to the database");
});

app.use(morgan('dev'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/create-user", function (req, res, next) {

    var user = new User();

    user.profile.name = req.body.name;
    user.password = req.body.password;
    user.email = req.body.email;

    user.save(function (err, user) {
        if (err) {
            res.send("deu erro");
        } else {
            console.log("Deu bom");
            res.send("deu bom");
        }
    })
})


app.get("/get-users", function (req, res, next) {
    User.find({})
        .exec(function (err, users) {
            if (err) res.send("Erro na hora de pegar os usuarios " + err);
            res.send(users);
        });
});



app.get('/', function (req, res) {
    res.send("Deu mais bom");
});



app.listen(80, function (err) {
    if (err) throw err;
    console.log("Server is running on port 80");
});

此外,当我连接到 mongolab 时,我收到警告:

DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using conn ect() or createConnection(). See http://mongoosejs.com/docs/connections.html#use-mongo-client Server is running on port 80 Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

但我没有在我的代码中使用任何 open() 方法,因为我没有使用默认的 mongoDB 库。我能够将一个集合添加到 mongolab 数据库,但数据不完整,现在我正在为此苦苦挣扎。

Edit2:这是我使用 bcrypt 的 UserSchema 的代码:

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var Schema = mongoose.Schema;

/* The user schema attributes/fields */
var UserSchema = new Schema ({
    email : String,
    password: String,




    profile: {
        name: {type: String, default: "Sem nome"},
        picture: {type: String, default: ''}
    },

    address: String,
    history: [{
        date: Date,
        paid: {type: Number, default: 0},
        //item: { type: Schema.Types.ObjectId, ref: ''}
    }]
});

/* The method to hash the password before saving it to the database */

UserSchema.pre('save', function(next){
    var user = this;
    if(!user.isModified('password')) return next();

    bcrypt.genSalt(10, function(err, salt){
        if(err) return next(err);

        bcrypt.hash(user.password, salt, null, function(err, hash){
            if(err) return next(err);
            user.password = hash;
            next();
        });
    });
});


/* Compare the password between the database and the input from the user */

UserSchema.methods.comparePasswords = function(inputpassword){
    return bcrypt.compareSync(inputpassword, this.password);
}


module.exports = mongoose.model('User', UserSchema);

感谢任何帮助,谢谢

最佳答案

要解决关于 mpromise 的第一个警告,您可以通过执行以下操作使用 native Promise( Node 版本 >= 6):

mongoose.Promise = global.Promise;

要解决第二个警告,您必须使用 useMongoClientdocumentation建议采用 promise 方法:

function connectDatabase(databaseUri) {
    var promise = mongoose.connect(databaseUri, {
        useMongoClient: true,
    });

    return promise;
}

connectDatabase('mongodb://root2:1234@ds161742.mlab.com:61742/ecommerce')
  .then(() => console.log("Connected to the database");)
  .catch((err) => console.log(err));

关于node.js - mongoose.save() 有两种类型的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45151589/

有关node.js - mongoose.save() 有两种类型的行为的更多相关文章

  1. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  2. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  3. ruby - Ruby gsub 替换中的行为不一致? - 2

    两个gsub产生不同的结果。谁能解释一下为什么?代码也可在https://gist.github.com/franklsf95/6c0f8938f28706b5644d获得.ver=9999str="\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleVersion\n\t0.1.190\n\tAppID\n\t000000000000000"putsstr.gsub/(CFBundleVersion\n\t.*\.).*()/,"#{$1}#{ver}#{$2}"puts'--------'putsstr.gsub/(CFBundleVersio

  4. ruby-on-rails - Ruby 中意外的大小写行为 - 2

    我在一段非常简单的代码(如我所想)中得到了一个错误的值:org=4caseorgwhenorg=4val='H'endputsval=>nil请不要生气,我希望我错过了一些非常明显的东西,但我真的想不通。谢谢。 最佳答案 这是典型的Ruby错误。case有两种被调用的方法,一种是你传递一个东西作为分支的基础,另一种是你不传递的东西。如果您确实在case中指定了一个表达式语句然后评估所有其他条件并与===进行比较.在这种情况下org评估为false和org===false显然不是真的。所有其他情况也是如此,它们要么是真的,要么是假的。

  5. ruby - 使对象的行为类似于 ruby​​ 中并行分配的数组 - 2

    假设您在Ruby中执行此操作:ar=[1,2]x,y=ar然后,x==1和y==2。是否有一种方法可以在我自己的类中定义,从而产生相同的效果?例如rb=AllYourCode.newx,y=rb到目前为止,对于这样的赋值,我所能做的就是使x==rb和y=nil。Python有这样一个特性:>>>classFoo:...def__iter__(self):...returniter([1,2])...>>>x,y=Foo()>>>x1>>>y2 最佳答案 是的。定义#to_ary。这将使您的对象被视为要分配的数组。irb>o=Obje

  6. ruby-on-rails - rails : check if the model was really saved in after_save - 2

    ActiveRecord用于在每次调用保存方法时调用after_save回调,即使模型没有更改并且没有生成插入/更新查询也是如此。这实际上是默认行为。在大多数情况下这没问题。但是一些after_save回调对模型是否实际保存的事情很敏感。有没有办法确定模型是否实际保存在after_save中?我正在运行以下测试代码:classStage 最佳答案 ActiveRecordusetocallafter_savecallbackeachtimesavemethodiscalledevenifthemodelwasnotchangedan

  7. ruby - 了解在 Ruby 中与 lambda 一起使用的 inject 行为 - 2

    我经常将预配置的lambda插入可枚举的方法中,例如“map”、“select”等。但是“注入(inject)”的行为似乎有所不同。例如与mult4=lambda{|item|item*4}然后(5..10).map&mult4给我[20,24,28,32,36,40]但是,如果我制作一个2参数lambda用于像这样的注入(inject),multL=lambda{|product,n|product*n}我想说(5..10).inject(2)&multL因为“inject”有一个可选的单个初始值参数,但这给了我......irb(main):027:0>(5..10).inject

  8. ruby-on-rails - rspec 测试 has_many :through and after_save - 2

    我有一个(我认为)相对简单的has_many:through与连接表的关系:classUser:user_following_thing_relationshipsendclassThing:user_following_thing_relationships,:source=>:userendclassUserFollowingThingRelationship还有这些rspec测试(我知道这些不一定是好的测试,这些只是为了说明正在发生的事情):describeThingdobefore(:each)do@user=User.create!(:name=>"Fred")@thing=

  9. ruby-on-rails - Assets 管道损坏 : Not compiling on the fly css and js files - 2

    我开始了一个新的Rails3.2.5项目,Assets管道不再工作了。CSS和Javascript文件不再编译。这是尝试生成Assets时日志的输出:StartedGET"/assets/application.css?body=1"for127.0.0.1at2012-06-1623:59:11-0700Servedasset/application.css-200OK(0ms)[2012-06-1623:59:11]ERRORNoMethodError:undefinedmethod`each'fornil:NilClass/Users/greg/.rbenv/versions/1

  10. ruby-on-rails - Rails - 理解 application.js 和 application.css - 2

    rails新手。只是想了解\assests目录中的这两个文件。例如,application.js文件有如下行://=requirejquery//=requirejquery_ujs//=require_tree.我理解require_tree。只是将所有JS文件添加到当前目录中。根据上下文,我可以看出requirejquery添加了jQuery库。但是它从哪里得到这些jQuery库呢?我没有在我的Assets文件夹中看到任何jquery.js文件——或者直接在我的整个应用程序中没有看到任何jquery.js文件?同样,我正在按照一些说明安装TwitterBootstrap(http:

随机推荐