Mongoose finds and creates multidimensional arrays

I am trying to get a user id and an array object that contains a specific location in places.

I want to do the following:

The query will return the result of placing the array.

If the user ID does not exist, create one and then return an array of the appropriate location.

If the location identifier is missing. create a new one, then return an array of the appropriate location.

How can i do this?

Current request:

easyCrime.findOne({ userid: userid, "locations.location": location }, {"locations.$.location": 1}).then(function (err, stats) { } }); 

Model:

  userid: { type: String, default: '57c1c0f3b6b20c011242bf22' }, locations: [ { userid: { type: String, default: '57c1c0f3b6b20c011242bf22' }, location: { type: Number, default: 1 }, easycrime: [ { optioname : { type: String, default: 'unknown' }, chance: { type: Number, default: 500 } } ], heavycrime: [ { optioname : { type: String, default: 'unknown' }, chance: { type: Number, default: 500 } } ], } ], timesteal: { type:Number, default: 0 } 
+7
javascript arrays mongodb mongoose
source share
1 answer

I assume easyCrime is a Model, because there is no such question as findOne in the document. If it is a model, name it EasyCrime.



It was very difficult for me to interpret your question. Based on what I understand, this is your decision.
 EasyCrime .findOne({ userid: param.userid}) .exec((err, crime) => { //userid not exists at all, create new if (!crime) { let newCrime = new EasyCrime({...}); newCrime.save(...); return; } //Check if location exists for (let i = 0; i < crime.locations.length; ++i) { if (crime.locations[i].location === param.location) { //crime.location[i] is what you're finding return; } } //Cannot find any location with provided param.location crime.locations.push({ userid: ..., location: param.location, ... }); crime.save(...); }) 
+1
source share

All Articles