Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 无法在Mongo(mongoose)中通过点符号搜索子文档_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js 无法在Mongo(mongoose)中通过点符号搜索子文档

Node.js 无法在Mongo(mongoose)中通过点符号搜索子文档,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,Mongo快把我逼疯了。我有以下模式: var userSchema = new Schema({ username: { type: String, require: true, unique: true }, password: { type: String, require: true, } }); var User = mongoose.model('user', userSchema); var deviceSchema = new Schem

Mongo快把我逼疯了。我有以下模式:

var userSchema = new Schema({
username: {
    type: String,
    require: true,
    unique: true
},
password: {
    type: String,
    require: true,
}
});
var User = mongoose.model('user', userSchema);

var deviceSchema = new Schema({
name: {
    type: String,
    require: true,
    unique: true
},
type: String,
lastvalue: {
    type: Schema.ObjectId,
    ref: 'event'
},
owner: {
    type: Schema.ObjectId,
    ref: 'user',
    require: true
},
apiKey: {
    type: String,
    unique: true,
    default: function() {
        return crypto.randomBytes(64).toString('hex');
    }
}
});
var Device = mongoose.model('device', deviceSchema);
我想检索用户的所有设备。因此:
Device.find({'owner.username':req.params.username})

但它返回一个空数组! 我也试过:
Device.find({'owner.username':req.params.username},{'owner':1})
Device.find({'owner.username':req.params.username},{'owner.$':1)
没有任何运气。。。
我已经搜索了整个互联网,但找不到任何有用的东西!

您需要先获取关联的用户
\u id
,然后使用第一次用户查询中的
\u id
字段在
所有者
字段中查询
设备
型号。以下显示了此方法:

User.findOne({ "username" : req.params.username }),
    .exec(function(err, user) {
        if (err) throw err;
        Device
        .find({"owner": user._id})
        .populate('owner', 'username') // only return the username
        .exec(function(err, devices) {
            if (err) throw err;
            console.log(JSON.stringify(devices, undefined, 4));
        });
    }
);

我可以在一个查询中完成吗?