英文:
How to push object to array which is in another array in MongoDB?
问题
我有一个Mongoose模式:
const UserSchema = new mongoose.Schema({
mail: {
type: String,
required: true
},
password: {
type: String,
required: true
},
folders: [
{
folderName: {
type: String,
default: 'Main',
required: true,
},
files: [
{
fileName: String,
fileType: String,
date: String,
filePath: String,
}
]
}
]
});
对于这个模式,我想从请求中获取用户的邮件和文件夹的名称,并将文件数据添加到这个文件夹中,但我不知道如何将文件推送到正确的文件夹中。
我想要实现这段代码:
const mail = req.body.mail;
const folderName = req.body.folderName;
const file = {
fileName: 'file222',
fileType: '.png',
date: '13-02-2022 21:15',
filePath: '/uploads',
}
const user = await userModel.findOne({ mail: mail });
const folders = user.folders.filter(folder => folder.folderName === folderName);
folders[0].files.push(file);
但在MongoDB中,类似这样的:
const userFile = await userModel.updateOne(
{ mail: mail, "folders.folderName": folderName },
{
$push: {
folders: {
files: file
}
}
}
);
但我不知道如何指定查询...我该怎么做?
英文:
I have a Mongoose Schema:
const UserSchema = new mongoose.Schema({
mail: {
type: String,
required: true
},
password: {
type: String,
required: true
},
folders: [
{
folderName: {
type: String,
default: 'Main',
required: true,
},
files: [
{
fileName: String,
fileType: String,
date: String,
filePath: String,
}
]
}
]
});
For this scheme, I would like to get the user's mail and the name of the folder from the request and add the file data to this folder, but I don't know how to push file to correct folder.
I want to do this code:
const mail = req.body.mail;
const folderName = req.body.folderName;
const file = {
fileName: 'file222',
fileType: '.png',
date: '13-02-2022 21:15',
filePath: '/uploads',
}
const user = await userModel.findOne({ mail: mail });
const folders = user.folders.filter(folder => folder.folderName === folderName);
folders[0].files.push(file);
but in MongoDB, something like this:
const userFile = await userModel.updateOne(
{ mail: mail, "folders.folderName": folderName },
{
$push: {
folders: {
files: file
}
}
}
);
But I don't know how to specify that query...
how can I supposed to do it?
答案1
得分: 0
以下是翻译好的内容:
const userFile = await userModel.updateOne(
{ mail: mail, "folders.folderName": folderName },
{
$push: {
"folders.$.files": file
}
}
);
文档
> 位置 $ 运算符标识要更新的数组中的一个元素,而不需要显式指定元素在数组中的位置。
英文:
const userFile = await userModel.updateOne(
{ mail: mail, "folders.folderName": folderName },
{
$push: {
folders.$.files: file
}
}
);
Docs
> The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.
答案2
得分: 0
尝试一下:
const userFile = await userModel.updateOne(
{ mail: mail, "folders.folderName": folderName },
{
$push: {
"folders.$.files": file
}
}
);
您可以在此处尝试更多:链接
英文:
Try it :
const userFile = await userModel.updateOne(
{ mail: mail, "folders.folderName": folderName },
{
$push: {
"folders.$.files":file
}
}
);
You can try more here: LINK
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论