node.js - 如何按 ID node.js 过滤猫鼬集合
问题描述
假设我有一个像这样的简单猫鼬模式
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String;
age: String,
created: { type: Date, default: Date.now }
})
module.exports = mongoose.model('User', UserSchema);
我可以很容易地找到所有用户集合User.find({})
。但我只想通过它们的_id 找到指定的集合。例如,我有 10 个用户集合,并且只想在这个动态数组中根据他们的 Id 查找用户
["5b66c0868278664f0d2f2fec","5b66c5a947eaed565b694efa"]
所以我需要使用where
or match
?
解决方案
你试过了$in
吗?
User.find({_id : {$in : ["5b66c0868278664f0d2f2fec","5b66c5a947eaed565b694efa"]})
$in 运算符选择字段值等于指定数组中的任何值的文档。要指定 $in 表达式,请使用以下原型:
User.find({ _id: { $in: ["5b66577c2f05bf1eb07956e0" ,"5b66b1879526eb0444d047cb"] }})
.then(users =>{
console.log("user", users)
})
推荐阅读
- java - Java早期阶段的UNO游戏问题
- unity3d - Collider2D 碰撞在 Unity 中不起作用
- r - 如何按数字向量和字符向量对数据帧进行排序
- javascript - Vuejs 项目在生产中包含 typescript.js
- android - 如何使用融合位置正确获取准确位置
- asp.net - 从移动应用程序调用时,WCF 缓存不起作用
- android - 我需要在 Kotlin 中使用按钮在 List 中添加输入
- ruby - 无法让 Cocoapods 在混合 Ruby 环境(OSX Sierra)中工作
- python - 由于“未定义名称'结果'”而出现错误
- javascript - 这些 javascript 函数以什么顺序运行?