Mongoose查找和创建多维数组。

7
我想获取用户ID以及包含位置信息的数组对象。
我想要实现以下目标:
查询将返回数组位置的结果。
如果根本没有用户ID,则创建它,然后返回匹配位置的数组。
如果位置ID号不存在,则创建一个新的位置ID,然后返回匹配位置的数组。
我该如何实现这个目标?
当前查询:
 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
    }

抱歉,我不明白你想要实现什么。如果你能提供查询示例和期望的结果,那会很有帮助。 - TomG
1个回答

1

我认为easyCrime是模型,因为文档中不存在findOne查询。如果它是模型,请将其命名为EasyCrime。



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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接