如何在mongoose中进行查询

时间:2018-02-09 11:02:26

标签: node.js mongodb mongoose

let UserSchema = new Schema({
created: {
    type: Date,
    default: Date.now,
    required: true
},
username: {
    type: String,
    unique: true,
    required: true
},
password: {
    type: String,
    required: true
},
role: {
    default: 'user',
    type: String, //we can consider using array of strings as in case user has several roles at the same time
    requierd: true
},
devices: [
    {
        id: '1',
        permissions:['start','stop']
    },

    {
        id: '2',
        permissions:['start','restart']
    }
]
});

当我在req.params.headers中收到新的{id:' 2',权限:['停止']}时,如何在不重复的情况下推送它。我需要检查是否为:' 2'已存在或不存在,那么我检查是否存在['停止']存在,然后如果它不存在我应该将其推送到收集中。

2 个答案:

答案 0 :(得分:0)

如果要查找与id或权限匹配的任何对象,可以使用$或操作数执行此操作,如下所示:

return User.findOne({ $or:[ {'devices.id': idValue}, {'devices.permissions': permission}  ]}).exec()
.then(user => {
    if(user) {
        console.log("We don't have to push it");
    } else {
        console.log("We have to push it");
    }
});

答案 1 :(得分:0)

您可以在declare -p foo declare -- foo="42" echo "$foo" 42 条件下使用function resolveAfter1() { return new Promise(resolve => { var scoresFromDb = db.account.find({}, { username: 1, score: 1 }).toArray(function(err, result) { if (err) throw err; // return result; }) setTimeout(() => { resolve('resolved'); }, 1000); }); } async function asyncCall() { var result = await resolveAfter1(); console.log(result); // here's your result return result; } asyncCall().then(result => console.log(result)); // console.log(asyncCall()); 来查找内部对象。为避免在数组中添加重复键,您可以使用update

elemMatch