首页 > 解决方案 > 如何按 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"]

所以我需要使用whereor match

标签: node.jsmongodbexpressmongoosemongoose-populate

解决方案


你试过了$in吗?

User.find({_id : {$in : ["5b66c0868278664f0d2f2fec","5b66c5a947eaed565b694efa"]})

$in 运算符选择字段值等于指定数组中的任何值的文档。要指定 $in 表达式,请使用以下原型:

User.find({ _id: { $in: ["5b66577c2f05bf1eb07956e0" ,"5b66b1879526eb0444d047cb"] }})
    .then(users =>{
        console.log("user", users)
    })

推荐阅读