Search code examples
mongodbexpressmongoosemongoose-schema

How to use default url for image in mongoose?


var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var url = "https://i.sstatic.net/34AD2.jpg";
var UserSChema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    profilePic: {type: String, default: url},
    username: String,
    password: String,
    isAdmin: {type: Boolean, default: false}
});

UserSChema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSChema);

The above mentioned is my code i tried that setting string as url and using that but its not working. Whenever i go and check the value in mongo shell the profilePic will be empty.


Solution

  • If there are already documents in your mongo collection it will not update the image URL for them in the database, It will add the default URL when you will save any new data and will also add it old record if you use mongoose to find them.

    So while using mongoose you will get the default value https://i.sstatic.net/34AD2.jpg always in your code but if see in mongo shell the profilePic for old documents will be empty.

    If you want to update the default value of profilePic in all the old documents also, run the below query in Mongo console.

    db.getCollection('users').updateMany({},{$set:{"profilePic": "https://i.sstatic.net/34AD2.jpg"}})