我正在尝试查找对另一个架构的引用并更新同级字段。具体来说,我尝试根据特定的“调查”ObjectId 操作下面的 hasResponded 字段。
我的架构如下所示:
var userSchema = new mongoose.Schema({
// some other stuff
surveys: [{
survey: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Survey'
},
hasResponded: {
type: Boolean,
default: false
}
}]
});
最佳答案
如果您有调查 ID,只需在数组中搜索具有此特定 ID 的所有用户即可。 类似这样的事情:
Users.find({surveys: { "$elemMatch": { type: <ID> } } });
然后,迭代用户及其相应的调查数组,以查找与您提供的 ID 匹配的用户。
不得不说,如果这个查询经常发生,我会稍微不同地构造这个数据库。
创建一个新的架构 - UserSurveys,其中包含用户的 ID 和调查 + hasResponded。像这样:
var UserSurveySchema = new mongoose.Schema({
user_id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
survey_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Survey'}
hasResponded: {type:Boolean, 'default':false}
...
});
您可能还想保留用户和调查 ID 的索引。
这样,更新字段就会容易得多,请求所需的时间也会短得多。
希望这有帮助。
关于node.js - 使用 Mongoose 查找byid 并更新同级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26630744/