mongoosefind并创buildmultidimensional array

我想获得用户标识,以及包含位置内特定位置的数组对象。

我想要完成的是以下内容:

查询将返回数组位置的结果。

如果不存在userid,则创build它,然后返回匹配位置的数组。

如果位置ID号码不存在。 创build一个新的,然后返回匹配位置的数组。

我怎样才能做到这一点?

当前查询:

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

模型:

  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 } 

我认为easyCrime是Model,因此在Document中没有findOne查询这样的事情。 如果是模型,请将其命名为EasyCrime。


我很难解释你的问题。 根据我的理解,这是你的解决scheme

 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(...); })