如何使用dot(。)通过Mongoose在Node.js中查询以及如何添加一个空数组

我有以下架构:

var userSchema = new Schema({ userID: Number, userName: String, userEmail: String, teams:Array, socialMedias: { fbUID: String, googleUID: String, twitter: String } }); 

首先,我如何添加一个空数组? 这是我正在做的以下方式吗?

 teams:{}, 

其次,我正在尝试在我的Node.js中使用Mongoose进行查询,但在点('。')中出现错误:

这是我正在保存的文件:

  var user = new users({ userID: id, //give the id of the next user in Dbase userName: userName, userEmail: 'userEmail', teams:{}, socialMedias: [{socialMediaType: socialMediaID}] }); 

其中userName,socialMediaType和socialMediaID是函数的参数。

所以,我添加这个文档后,我试图做下面的查询:

 function searchUser(socialMediaID, socialMediaType){ var user users.findOne({socialMedias.socialMediaType: socialMediaID}, function(err, userFound){ if(err) return handleError(err); user = userFound; }); //what does MongoDb return if it does not find the document? return user; } 

但我在这里得到一个错误:

 socialMedias.socialMediaType 

那么,我该如何做这个查询呢?

我试图find在Mongoose文档,但我没有find。

谢谢你的理解。

这里有很多问题,你可能会遇到。

首先,团队是一个数组属性,但是你正在为它分配一个对象。 你需要做这样的事情:

 var user = new users({ userID: id, //give the id of the next user in Dbase userName: userName, userEmail: 'userEmail', teams:[], socialMedias: [{socialMediaType: socialMediaID}] }); 

其次,如果将socialMediaType作为函数parameter passing,则不能像使用它那样使用它。 你需要做这样的事情:

 var socialMedias = {}; socialMedias[socialMediaType] = socialMediaID; var user = new users({ userID: id, //give the id of the next user in Dbase userName: userName, userEmail: 'userEmail', teams:[], socialMedias: [socialMedias] }); 

第三你的findOne不会按原样工作。 从我能在这里收集你的意图,你需要这样的东西:

 function searchUser(socialMediaID, socialMediaType){ var user var query = {}; query["socialMedias."+socialMediaType] = socialMediaID; users.findOne(query, function(err, userFound){ if(err) return handleError(err); user = userFound; }); //what does MongoDb return if it does not find the document? return user; } 

但是,第四,即使这样也行不通,因为你正在同步地从执行和asynchronous操作的方法返回用户。 有很多方法可以解决这个问题,但是您可以先阅读承诺,或者将callback函数传递给searchUser。