Node.js 无法在Mongo(mongoose)中通过点符号搜索子文档
Mongo快把我逼疯了。我有以下模式: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
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));
});
}
);
我可以在一个查询中完成吗?