Mongoose does not save data in MongoDB


The following is the object literal I'm trying to save in MongoDB. It is defined in the app.js file, which is an Express server. Since the object is hard-coded on the server, I assumed that a new copy would be saved in the database each time I start the server, or at least the document would be saved once and redefined or left unchanged when it was detected that the new document was identical to that that was saved the last time the server was started. To my surprise, not only copies are created in MongoDB, but the document is not saved at all. However, a news collection was created as verified with the mongo shell show collections. Also, I am not getting any errors in the callback function. I also tried Model.create (doc, fn) in my Express / News route, but this also does not work (the document needs to be saved every time the client / news channel is called by the client, but it is not). What am I missing?
Please read my annotations labeled "<-" to see what other problems or unexpected behavior I encounter. I will be very grateful if you can address them also in your answer.

var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path') , fs = require('fs'); // Defining connection to the database: var mongoose = require('mongoose'). connect("mongodb://localhost:27017/my-test-db"), db = mongoose.connection; var Schema = mongoose.Schema; var ObjectID = Schema.ObjectId; // Setting up the debug flag: mongoose.set('debug, true'); // Logging connection: db .on('error', console.error.bind(console, 'DB connection error.')) .once('open', console.log.bind(console, 'DB Connection established.')); // Defining MongoDB schemas: var usr = new Schema({ first: String, last: String }); var newsSchema = new Schema({ headline: String, bd: String, imgURI: String, imgThumbURI: String, imgCaption: String, addedOn: Date, addedBy: { type: ObjectID, ref: 'usr' } // On user action 'save' populate the addedOn and addedBy fields before the news article is actually saved to the DB: newsSchema.pre('save', function(next){ if( !this.addedOn ) this.addedOn = new Date(); if( !this.addedBy ) this.addedBy = {first: "admin", last: "admin"}; }); // Indexing important fields: usr.index({last: 1}); newsSchema.index({headline: 1}); //Adding the News model: var News = mongoose.model('news', newsSchema); var nws1 = new News({ headline: "Test news Headline", bd: "Test news body. Test news body. Test news body. Test news body. Test news body. ", imgURI: encodeURI("images/news/img.jpg"), imgThumbURI: encodeURI("images/news/thumbs/img.jpg"), imgCaption: "Test news image caption.", addedOn: new Date(), addedBy: {first: "Admin", last: "Admin"} }); nws1.save(function(err, news){ if(err) return console.error("Error while saving data to MongoDB: " + err); // <- this gets executed when there an error console.error(news); // <- this never gets logged, even if there no error. }); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.resolve(__dirname + '/public')); app.set('view engine', 'html') .engine('html', function(path, options, fn){ if('finction' == typeof options){ fn = options, options = {}; } fs.readFile(path, 'utf8', fn); }); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.session()); app.use(express.static(path.join(__dirname, 'public'))); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); 

thank you for your time
Regards, Jared

+6
source share
3 answers

It seems like the problem is keeping the middleware of your news scheme.

 newsSchema.pre('save', function(next){ if( !this.addedOn ) this.addedOn = new Date(); if( !this.addedBy ) this.addedBy = {first: "admin", last: "admin"}; }); 

Your function receives the β€œnext” callback that you must complete to let mongoose know that you are done and ready to save the document. Since you do not name it, this may explain why you are not saving anything, as well as any errors.

Just try calling as follows:

 newsSchema.pre('save', function(next){ if( !this.addedOn ) this.addedOn = new Date(); if( !this.addedBy ) this.addedBy = {first: "admin", last: "admin"}; next(); }); 
+24
source

I found several problems while trying to reproduce this locally.

You do not call next () in newsSchema.pre ('save')

Must be

 newsSchema.pre('save', function(next){ if( !this.addedOn ) this.addedOn = new Date(); if( !this.addedBy ) this.addedBy = adminUser; next(); }); 

You also need to make sure you are connected to db before doing any of this, not sure if you are or not, since I have not seen this part of the code.

+4
source

My code was different, but my result was apparently the same: apparently, I did not save in Mongo, despite the call to .save. HOWEVER, salvation actually took place, I just did not understand what some parameters of Mongoose mean, and that it takes some freedom to get the name of your collection.

More specifically, when you use:

 mongoose.model('MyModelName', invitationSchema); 

to form your collection name, your model name is converted to lowercase, and "s" is added (if not). See Also http://samwize.com/2014/03/07/what-mongoose-never-explain-to-you-on-case-sentivity/

You can, if you want, get around these collection naming conventions to some extent by using the collection name option when creating a schema. See http://mongoosejs.com/docs/guide.html#collection

Here's mine:

 const modelName = "SharingInvitation"; const collectionName = modelName + "s"; const numberOfHoursBeforeExpiry = 24; var expiryDate = new Date (); expiryDate.setHours(expiryDate.getHours() + numberOfHoursBeforeExpiry); var invitationSchema = new Schema({ // _id: (ObjectId), // Uniquely identifies the invitation (autocreated by Mongo) // gives time/day that the invitation will expire expiry: { type: Date, default: expiryDate }, // The user is being invited to share the following: owningUser: ObjectId, // The _id of a PSUserCredentials object. capabilities: [String] // capability names }, { collection: collectionName }); 
0
source

Source: https://habr.com/ru/post/951814/


All Articles