javascript - 使用 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"
]
}
解决方案
要使用 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 } });
推荐阅读
- html - 有时不会触发DIV内的Ionic 4 App点击事件
- api - Strava - 如何检测运行/活动中的暂停
- javascript - Google 云端硬盘电子表格超出了最长执行时间
- python - 附加到python中的列表列表
- swift - 防止在闭包的参数上保留/释放快速关闭?
- java - 从数组中删除学生的问题会产生错误
- switch-statement - 如何在 switch 语句中进行计算?
- asp.net - Visual Studio 19 在添加引用时抛出错误
- javascript - 每次我在新标签页中打开时,VueJS 都会要求登录
- python-3.x - SeleniumPython3.x 我该如何处理这个元素?