These are chat archives for Automattic/mongoose

1st
Jun 2016
Nick Rameau
@R4meau
Jun 01 2016 14:59
Hi everyone, I got a little problem with an update query here
Suppose I have this model:
var stuffSchema = new mongoose.Schema({
  "id": 1,
  "cars": {
    "suv": [],
    "sports": [],
    "supercar": [{
      "owner": "nick",
      "previousOwners": [
        ObjectId("574e1bc0abfb4a180404b17f"),
        ObjectId("574e1bdeabfb4a180404b180"),
        ObjectId("574e1c4babfb4a180404b181"),
        ObjectId("574e1c67abfb4a180404b182"),
        ObjectId("574e23abd25baf340e678b2d"),
        ObjectId("574e241ec8caa3a81cc85ed5")
      ]
    }]
  }
});

var Stuff = mongoose.model('Stuff', stuffSchema);
I want to add a previousOwners if a specific owner already exists and add a new owner with its respective previousOwner if the specific owner does not exist yet.
Here's what I tried
Stuff.update({
  id: 1,
  'cars.supercar.owner': 'olix'
}, {
  $addToSet: {
    'cars.supercar.previousOwners': ObjectId("574e241ec8caa3a81c893e73")
  }
}, {
  $upsert: true
}, function(err) {
  if (err) {
    console.log('Error: ' + err);
  }
});
Mohamed Nasrullah
@nasr18
Jun 01 2016 15:04
cars.supercar is an array. so u need to give cars.supercar[0].owner @R4meau
Nick Rameau
@R4meau
Jun 01 2016 15:05
@nasr18 My bad, I forgot to add it in the example. I did it. It's still not working
Stuff.update({
  id: 1,
  'cars.supercar.owner': 'olix'
}, {
  $addToSet: {
    'cars.supercar.$.previousOwners': ObjectId("574e241ec8caa3a81c893e73")
  }
}, {
  $upsert: true
}, function(err) {
  if (err) {
    console.log('Error: ' + err);
  }
});
@nasr18 :point_up:
Mohamed Nasrullah
@nasr18
Jun 01 2016 15:07
inside first object of update.
Nick Rameau
@R4meau
Jun 01 2016 15:07
Oh, okay
Hold on, let me try
Mohamed Nasrullah
@nasr18
Jun 01 2016 15:07
Stuff.update({
  id: 1,
  'cars.supercar.owner': 'olix'
}, {
Nick Rameau
@R4meau
Jun 01 2016 15:08
@nasr18 Still not working
Stuff.update({
  id: 1,
  'cars.supercar.$.owner': 'olix'
}, {
  $addToSet: {
    'cars.supercar.$.previousOwners': ObjectId("574e241ec8caa3a81c893e73")
  }
}, {
  $upsert: true
}, function(err) {
  if (err) {
    console.log('Error: ' + err);
  }
});
Mohamed Nasrullah
@nasr18
Jun 01 2016 15:10
first fetch the record using find and then see whether its correct or not
Nick Rameau
@R4meau
Jun 01 2016 15:13
Ok
@nasr18 Yes, using find returns the document
db.stuffs.find({id: 1, 'cars.supercar.owner': 'nick'})
works fine, it returns the document. @nasr18
Nick Rameau
@R4meau
Jun 01 2016 15:39
If anyone can help, answer my question over there
LeonineKing1199
@LeonineKing1199
Jun 01 2016 15:51
You could just pull the document in, edit it manually and then save it.