0

I want to add a user inside the array objects, and add two more rows while inserting.

These are the two mongoose models that are used.

module.exports = mongoose.model('Users', {

      id:String, //the same id as user.id
      nick:String, //the same nick as user.nick

    }); 


module.exports = mongoose.model('Stores', {

  id: String,
  user: [{
    id: String, 
    nick: String,
    nr: Number,
    earnings: Number
  }],
  total: Number

}); 

So let's say I want to insert a Users that is found by its id(not the auto-generated). (I have the removed the if (err) to make it readable). This how i try to solve right now.

  Users.findOne({id : req.body.userid }, function(err, user) {

  //what user contains 
  user = { _id: 551fb0b688eacdf0e700000c,
      id: '123abc',
      nick: 'Foo',
      __v: 0 }

//I want to add this into the user and push it into exsisting array of        
objects that is 'users'
//But before that i want to add more info to the user,

//the desired format that I want to insert into 'users'
user = {id: '123abc',
       nick: 'Foo',
       nr: req.body.nr, //new
       earnings: req.body.earnings} //new

    Stores.update({id: req.params.id},
         {$push: { 'users' : user }}, function(err, store) {



    });

});


The current result is the following.
users: [
        {
            id: "123abc",
            nick: "Foo"

        }]

How can I solve this?

1 Answer 1

2

The schema design as is creates at least one problem. What if a user updates their nick? Rather than only updating the Users collection you would also need to update every document in Stores that matches the user. You could use a ref and then populate to negate this concern.

module.exports = mongoose.model('Users', {
  id: String, //the same id as user.id
  nick: String, //the same nick as user.nick
});

module.exports = mongoose.model('Stores', {
  id: String,
  users: [{
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Users'
    },
    nr: Number,
    earnings: Number
  }],
  total: Number
});

Now the query would be:

Users.findOne({
  id: req.body.userid
}, function(err, user) {
  Stores.update({
    id: req.params.id
  }, {
    $push: {
      'users': {
        user: user,
        nr: req.body.nr, //new
        earnings: req.body.earnings
      }
    }
  }, function(err, store) {});
});

Later when you need to query Stores:

Stores
  .find(QUERY)
  .populate('users')
  .exec(function(err, stores) {...
  });
Sign up to request clarification or add additional context in comments.

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.