首页 > 解决方案 > 使用 findById 时无法在数组中传递多个文档

问题描述

我想通过它们的 id 找到数组中的每个元素,并将其与发布请求一起发送以创建一个新帖子。现在,当我创建一个新帖子时,只传递数组的第一个索引,如果我使用 find(),它会传递所有社交模式,无论它是否在请求的正文中。我希望这是有道理的,如果它不请让我知道。我希望有人能帮帮忙。

下面是同样使用 Joi 的 qrcode 帖子的猫鼬模式

const Joi = require("joi");
const mongoose = require("mongoose");
const { themeSchema } = require("./Theme");
const { userSchema } = require("./User");
const { socialSchema } = require("./Social");

const QrCode = mongoose.model(
  "QrCode",
  new mongoose.Schema({
    user: {
      type: userSchema,
      required: true,
    },
    name: {
      type: String,
      maxLength: 255,
      required: true,
      trim: true,
    },
    theme: {
      type: themeSchema,
      required: true,
    },
    // Social Media Links
    social: [
      {
        type: socialSchema,
        required: true,
      },
    ],
  })
);

function ValidateQrCode(qrCode) {
  const schema = {
    userId: Joi.objectId(),
    name: Joi.string().max(255).required(),
    themeId: Joi.objectId().required(),
    socialId: Joi.array().required(),
  };

  return Joi.validate(qrCode, schema);
}

module.exports.QrCode = QrCode;
module.exports.validate = ValidateQrCode;

这是创建新二维码的发布路线

router.post("/", auth, async (req, res) => {
  const { error } = validate(req.body);
  if (error) res.status(400).send(error.details[0].message);

  const theme = await Theme.findById(req.body.themeId);
  if (!theme) return res.status(400).send("Invalid theme.");

  const user = await User.findById(req.user._id);
  if (!user) return res.status(400).send("Invalid theme.");

  const social = await Social.findById(req.body.socialId);
  if (!social) return res.status(400).send("Invalid social.");

  const qrCode = new QrCode({
    user: user,
    name: req.body.name,
    theme: theme,
    social: social,
  });

  await qrCode.save();

  res.send(qrCode);
});

在我的邮递员请求正文中,我正在输入以下信息

{
    "name": "Friends",
    "themeId": "60f89e0c659ff827ddcce384",
    "socialId": [
        "60f89e43659ff827ddcce386",
        "60f89e5c659ff827ddcce388"
    ]
}

标签: javascriptnode.jsexpress

解决方案


要使用 id 获取数据,您可以简单地使用以下 mongodb 查询,

db.collection.find( { _id : { $in : ["1", "2"] } } );

在猫鼬中,

model.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('1'),
        mongoose.Types.ObjectId('2'), 
        mongoose.Types.ObjectId('3')
    ]}
}, function(err, docs){
     console.log(docs);
});

或者

 await Model.find({ '_id': { $in: ids } });

推荐阅读