node.js Mongoose 实例 .save() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35733647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:59:48  来源:igfitidea点击:

Mongoose instance .save() not working

node.jsmongodbmongoose

提问by Ahmet Can Güven

I have a problem with Mongoose and MongoDb

我有猫鼬和 MongoDb 的问题

It is very interesting that only Model.updateworks and savenever works and does not even fire callback.

非常有趣的是,它只Model.update工作而save从不工作,甚至不触发回调。

Mongoose: 4.4.5 MongoDB: 3.0.8

猫鼬:4.4.5 MongoDB:3.0.8

Express Route

快速路线

var mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/db");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(callback) {
    console.log("connection to db open")
});
var User = require("../models/user.js");

User Model

用户模型

var user = new Schema({
    uid: { type: Number, required: true, unique: true},
    hwid: { type: String, default:""},
    bol:{type:String,default:""}
});

Update Enpoint

更新端点

Working version: Model.update()

工作版本:Model.update()

User.update({_id: id}, {
    uid: 5, 
}, function(err, numberAffected, rawResponse) {
    console.log(err);
})

Not working version and I have to solve this: Object.save()

不工作的版本,我必须解决这个问题:Object.save()

User.find({_id:id}, function(err,user){
    if(err){
         console.log(err);
    }
    if(!user){
         console.log("No user");
    }else{
        user.uid = 5;
        user.save(function(err,news){
            console.log("Tried to save...");
        });
    }
    console.log("At least worked");
})

Even callback is not firing. Connection successfully opens. It never invokes callback.

甚至回调也没有触发。连接成功打开。它从不调用回调。



  1. Tried to use var User = connection.model('User', schema)didn't work.
  1. 尝试使用var User = connection.model('User', schema)没有用。

回答by Abolfazl Miadian

I have the same problem. my problem was about changing an array inside db, then when I try to use .save(), it didn't understand that I changed any thing, then the .save() didn't work. I just use markModified() before use .save() and my problem become solved.

我也有同样的问题。我的问题是关于更改 db 中的数组,然后当我尝试使用 .save() 时,它不明白我更改了任何内容,然后 .save() 不起作用。我只是在使用 .save() 之前使用 markModified() ,我的问题就解决了。

this is my code with problem: (not working)

这是我的代码有问题:(不工作)

club.members[index].name = new_name;
club.save();

this is my solved code: (working)

这是我解决的代码:(工作)

club.members[index].name = new_name;
club.markModified('members');
club.save();

enjoy!

请享用!

回答by Ahmet Can Güven

I am not going to delete this question because people may encounter this problem too. Actually problem was not related with MongoDb or Mongoose. When you call Object.save()responsibility chain is like below:

我不会删除这个问题,因为人们也可能会遇到这个问题。实际上问题与 MongoDb 或 Mongoose 无关。当您调用Object.save()责任链时,如下所示:

  1. Schema.pre("save")
  2. Save data to dabe
  3. Schema.post("save")
  1. Schema.pre("保存")
  2. 将数据保存到 dabe
  3. Schema.post("保存")

So if you block pre("save")and don't call next()handler you won't be able to save your document. This was my case, I forgot the next()call inside an if statement and tried to find the error for more than 3 hours.

因此,如果您阻止pre("save")并且不调用next()处理程序,您将无法保存您的文档。这是我的情况,我忘记了next()if 语句中的调用,并试图找到错误超过 3 个小时。

user.pre("save", function(next) {
    if(!this.trial){
        //do your job here
        next();
    }
}

When this.trial == true, next handler won't be reachable.

当 时this.trial == true,将无法访问下一个处理程序。

To prevent errors like this we should take care of branch coverage, reporters can show us untested codes. Your problem might be related with this too. Be sure you are calling next()if your document should be saved.

为了防止这样的错误,我们应该注意分支覆盖,报告者可以向我们展示未经测试的代码。您的问题也可能与此有关。如果您的文档应该被保存,请确保您正在调用next()

Fixed Version

固定版

user.pre("save", function(next) {
    if(!this.trial){
        //do your job here
    }
    next();
}

回答by Salx

This sounds nuts.. and I've been trying to work through this problem for hours. Looked at so many stack overflow posts.. it's unbelievable.

这听起来很疯狂……而且我已经尝试解决这个问题好几个小时了。看了这么多堆栈溢出的帖子..真是难以置信。

And you know what it was? I wasn't specifying the database at the end of the url.

你知道那是什么吗?我没有在 url 的末尾指定数据库。

So instead of

所以代替

"mongodb://127.0.0.1:27017/test"

I had

我有

"mongodb://127.0.0.1:27017

I wasted a whole day on this. I really wish I was given errors of some kind. Saving a record always returned ok. And in the database log, I was connecting ok. But I really needed to look at the details. Yes, it was connecting to the mongo instance, but not to the database itself. ugh!

我在这上面浪费了整整一天。我真的希望我得到某种错误。保存记录总是返回正常。在数据库日志中,我连接正常。但我真的需要看看细节。是的,它连接到 mongo 实例,而不是连接到数据库本身。啊!

回答by dodo

Like Paul said. Most likely you are calling save on the 'req.user' object, which is not a Mongoose object. Make sure you are doing something like this:

就像保罗说的。很可能您是在 'req.user' 对象上调用 save,该对象不是 Mongoose 对象。确保你正在做这样的事情:

//I am using your 'user' schema
var userModel = mongoose.model('User', user);
var User = mongoose.model('User');
var newUser = new User(req.user);
newUser.save(function(error, user){
   //your code
}

回答by Anselm

Just in case this happens to anyone else.

以防万一其他人发生这种情况。

Another cause of this could be if you do not have an open connection to your mongodb instance. Check your output for the appropriate connection feedback.

另一个原因可能是您没有与 mongodb 实例的开放连接。检查您的输出以获得适当的连接反馈。

[initandlisten] connection accepted from 127.0.0.1:40448 #1 (1 connection now open)

[initandlisten] 从 127.0.0.1:40448 #1 接受的连接(现在打开 1 个连接)

回答by Saurabh

I came across the same issue, turns out that instance.save()returns a promise. So all you need to do is handle the promise. Using async/await-

我遇到了同样的问题,结果是instance.save()返回一个承诺。所以你需要做的就是处理这个承诺。使用async/await-

await instance.save()

回答by SM J

for anyone having same error as me.. If you call .save() twice in very short time. the last call will be discarded. My problem was this.

对于与我有相同错误的任何人.. 如果您在很短的时间内调用 .save() 两次。最后一个呼叫将被丢弃。我的问题是这个。

//module usersave(userData)
{
  await userData.save()
}
//module A
{...todos
  moduleB(userData)
  ...some todos that doesn't take much time.
  await usersave(userData) //second call
}
//module B(userData)
{
 ...todos;
 await usersave(userData) // first call
}

=> Object.save() was called at module B, and instantly called again at module A. (it doesn't matter you made save module or just directly called Object.save() ). these kinds of call stack emits no error, and normal success return on both modules. However, since second call is evoked before the mongodb actually reflects the change, later call is just discarded. problem is that it returns as if they are actually saved so you can't catch an error.

=> Object.save() 在模块 B 中被调用,并立即在模块 A 中再次被调用。(不管你是创建了 save 模块还是直接调用了 Object.save() )。这些类型的调用堆栈不会发出错误,并且两个模块都返回正常的成功。但是,由于在 mongodb 实际反映更改之前调用了第二个调用,因此只会丢弃后面的调用。问题是它返回就好像它们实际上已保存一样,因此您无法捕获错误。

solution : just put an await. await new Promise(r=>setTimeout(r,2000)) will do.

解决方案:只需等待。await new Promise(r=>setTimeout(r,2000)) 会做。