$ addToSet object for array in mongoose

I have a collection in which documents of several products are stored. The document has an evaluation array for storing user pricing objects on the product.

Here is an example of a custom object:

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

Can someone tell me if it is possible to do โ€œPaste into duplicate updateโ€ into evaluation array? I tried $addToSet , but when the object is clicked on evaluation , the _id property is added to the user object, although I do not have it in the model, for example:

 { "_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") } 

How does $addToSet to use the id field to validate a duplicate 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(); }) }) 
+5
source share
1 answer

You can prevent Mongoose from adding the _id field to the elements of the evaluation array 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}); 
+4
source

Source: https://habr.com/ru/post/1210802/


All Articles