6

I have a collection that stores documents of a few products. In the document, there's an array evaluation to store objects of users' price evaluations on a product.

Here's an example of user object:

var data = {user_id:90,price:400}

Can anyone tell me if it's possible to do an "Insert on duplicate update" on the evaluation array? I have tried $addToSet , but when an object is push into the evaluation, there is an _id property added to the user object, even though I don't have it in the model, like this:

{
  "_id": 54b13f52604fc5d242d4aa68,
  "__v": NumberInt(0),
  "evaluation": [
    {
      "price": NumberInt(14616),
      "user_id": NumberInt(91),
      "_id": ObjectId("54b13f5e604fc5d242d4aa6b") // Why is it added?
    },
    {
      "price": NumberInt(16211),
      "user_id": NumberInt(92),
      "_id": ObjectId("54b140d1604fc5d242d4aa74") //
    }
  ],
  "product": [
   {
      "title": "ABC",
      "model_id": "382",
      "id": "513",
      "category": "1",
      "src": "xxx.jpg"
    }
  ],
  "timestamp":ISODate("2015-01-10T15:03:46.310Z")
}

Is that how $addToSet works to use the id field to check for duplicated object?

model.js

var evaluation = new mongoose.Schema({
       product:[],
       timestamp : { type : Date, default: Date.now },
       evaluation:[{user_id:Number,price:Number}],
},{strict:false});

var models = {
      Eva:mongoose.model('Evaluation',evaluation)
    };

app.js

var mongo_models = require('./db/mongo_model')(mongoose);
Eva = mongo_models.Eva;

io.on('connection', function(socket){
  socket.on("evaluation",function(d){
    var data = {user_id:user_id,price:d.price};
    Eva.update({_id:d.tid},{$addToSet:{evaluation:data}}).exec();
  })
})
RedGiant
  • 4,444
  • 11
  • 59
  • 146
  • 3
    Add `{ _id : false }` to your schema, that way mongoose won't create `_id`s for sub documents. - http://stackoverflow.com/questions/17254008/stop-mongoose-from-created-ids-for-subdocument-arrays – BatScream Jan 10 '15 at 16:43
  • the original question needs to specifiy the problem they are trying to solve – Alexander Mills Nov 06 '15 at 21:52

1 Answers1

5

You can prevent Mongoose from adding a _id field to the evaluation array elements by declaring an inline schema for the elements and disabling _id:

var evaluation = new mongoose.Schema({
   product:[],
   timestamp : { type : Date, default: Date.now },
   evaluation:[Schema({user_id:Number,price:Number}, {_id: false})],
},{strict:false});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471