5

I'm new with mongo and mongoose and I'd like to know how we can add, delete or edit an object in the database when we have an embedded data model as follow :

var userSchema = mongoose.Schema({

    local            : {
        email        : String,
        password     : String,
    },

    houses             : [

        {
            phone_numbers : [ {number: String} ],
            adresse         : String,

        }

     ]

    });


    module.exports = mongoose.model('User', userSchema);

For example, I would like to add a new "house" to my user.

So I tried :

            User.findById(req.user.id, function(err, user){

                user.houses.adresse = 'TEST';
                user.save();

             });

But it does not seem to work and I didn't find how to do that in mongoose docs. Any idea on how I could accomplish that ?

Thanks for your help !

1

2 Answers 2

16

You can separate model for readability, and you can use House model to add sub docs to User like;

User.js

var House = require("House");

var userSchema = mongoose.Schema({

    email : String,
    password : String,
    houses : [ House.schema ]

});

module.exports = mongoose.model('User', userSchema);

House.js

var houseSchema = mongoose.Schema({

    phone_numbers : [ String ],
    adresse         : String,

});


module.exports = mongoose.model('House', houseSchema);

In your controller;

var User = require("models/User");
var House = require("models/House");

......


User.findById(req.user.id, function(err, user){

    var houseModel = new House();
    houseModel.adresse = "TEST";
    user.houses.push(houseModel);
    user.save();
 });
Sign up to request clarification or add additional context in comments.

Comments

1

//Craete an object and assign it the existing embedded doc.
var item = { houses: req.user.houses };
// add your new address into the existing object
item.houses.push({adresse:'Test'})

// $set below updates the whole document along with your new address
User.findByIdAndUpdate(req.user.id, { $set: item }, function(err, result) {
  if (err) {
      callback(err, undefined);
  } else if (result) {
      callback(err, result);
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.