Search code examples
javascriptmongoosemongoose-schema

Mongoose Remove key(s) from child schema (nested subdocuments)


I have two schemas defined, imageSchema and userSchema. imageSchema has key postedBy: userSchema. Question is shall I remove unused attributes of userSchema (like password) when nested into imageSchema, if so how to do it?

var userSchema = new mongoose.Schema({
  email: String,
  password: String,
  name: String,
}, {versionKey: false})

var imageSchema = new mongoose.Schema({
  filePath: String,
  user: userSchema,
  createdAt: Date,
  comments: [{body: "String", by: mongoose.Schema.Types.ObjectId}]
})
...
app.post("/upload-image", async function(req, res){
  if(req.session.user_id) {
    ...
      fileSystem.rename(oldPath, newPath, function(err2){
        getUser(req.session.user_id, function(user){
          delete user.password
          var currentTime = new Date().getTime()
          Image.create({
            "filePath": newPath,
            "user": user,
            "createdAt": currentTime,
            "comments": []
          }, function(err2, data){
            res.redirect("/?message=image_uploaded")
          })
...

So after I created a new document of Image, I checked the database, the user field of the new Image has the attribute of password, which is not desired. "delete user.password" seems not working. How should I delete this attribute? Shall I do it when defining the imageSchema, or remove it when posting the data (the app.post part)?


Solution

  • This can be done is multiple ways. The way i like is to exclude the field from schema and also exclude while insertion.

    Exclude from schema

    var imageSchema = new mongoose.Schema({
      filePath: String,
      user: userSchema.pick(["email", "name"]), // this will return schema with only email and name from the schema
      createdAt: Date,
      comments: [{body: "String", by: mongoose.Schema.Types.ObjectId}]
    })
    

    Exclude while inserting

    we are omitting the user here before insertion this can be also done with underscore/lodash _.omit(user, 'password')

    getUser(req.session.user_id, function({password, ...user}){
             Image.create({
                "filePath": newPath,
                "user": user,
                "createdAt": Date.now(),
                "comments": []
              })
    }