mongoose .save() doesn't work

2020-07-03 08:06发布

I have those code running try to save an object into MongoDB.

The .save() never got success run. the code running fine.

.save() method doesn't work.

var conn = mongoose.createConnection(mongoUrl, {auth: {authdb: "admin"}});
conn.on('error', function (err) {
    throw err;
});
conn.once('open', function callback() {
    console.log("connected to " + mongoUrl);
    var cacheSchema = mongoose.Schema({}, {strict: false});
    cacheSchema.set('collection', 'caches');
    // you need to specify which connection is uing.
    var Cache = conn.model('cache', cacheSchema);
    var measure = new Cache();
    measure['test'] = "test";
    measure.save(function(err){
        console.log('test');
    });
});

2条回答
霸刀☆藐视天下
2楼-- · 2020-07-03 08:37

Please read this part of documentation from mongoose and try the following:

   var measure = new Cache({test:'teste'}); 
   // or measure.set('test', 'teste');
   measure.save(function (err) {
                    console.log(err);
                });

You will be able to see the issue if there's any.

Update the issue is using:

var Cache = conn.model('cache', cacheSchema);

instead of

var Cache = mongoose.model('cache', cacheSchema);
查看更多
疯言疯语
3楼-- · 2020-07-03 08:43

I just ran into a similar issue in my code. For mine, I was dealing with an object within my user document. I had to run a user.markModified('object') before the user.save() to ensure the changes were saved to the database. My running theory is that Mongoose wasn't tracking items unset or removed from the database automatically

查看更多
登录 后发表回答