Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose .save() doesn't work

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');
    });
});
like image 490
Peter Huang Avatar asked Oct 02 '15 18:10

Peter Huang


People also ask

What does save () do in Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

Does Mongoose save return a Promise?

While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

What is difference between save and create in Mongoose?

1 Answer. The . save() is considered to be an instance method of the model, while the . create() is called straight from the Model as a method call, being static in nature, and takes the object as a first parameter.


2 Answers

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

like image 67
Zak Holt Avatar answered Sep 20 '22 08:09

Zak Holt


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);
like image 45
Alvaro Joao Avatar answered Sep 19 '22 08:09

Alvaro Joao