Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$addToSet an object to an array in mongoose [duplicate]

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();
  })
})
like image 722
RedGiant Avatar asked Jan 10 '15 15:01

RedGiant


1 Answers

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});
like image 192
JohnnyHK Avatar answered Nov 07 '22 13:11

JohnnyHK