Mongoose doesn't save data to the MongoDB

前端 未结 3 883
情歌与酒
情歌与酒 2021-02-04 18:02


Below is an object literal I am trying to save to MongoDB. It is defined within the app.js file which is an Express server. As the object is hardcoded within the server, my

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 18:20

    It looks like the problem is in your news schema's save middleware.

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

    Your function receives a "next" callback which you must execute to let mongoose know that you are done and ready to save the document. Since you're not calling it, it could explain why you get nothing saved, and also no errors.

    Try just calling next like this:

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

提交回复
热议问题