node.js - 猫鼬推送到数组
问题描述
我需要将一个对象推入数据库中的数组中,但出现错误。我究竟做错了什么 ?我发现了这样一个主题Push items into mongo array via mongoose but can't proper apply ..................... ..................................................... ..................................................
habalka.files.push({_id: "tata", destination: "Harry"});
habalka.save((res) => {
console.log(res)
});
当我尝试这段代码时,我得到了这个答案
MongooseError:文档在保存之前必须有一个_id
数据库
{
"_id": "78935e75-86c0-47c2-a76d-2b52a0a71e7c",
"files": [
{
"_id": "67e848e5-7fb0-480b-a1d3-f3a09d1b57f7",
"destination": "./uploads/78935e75-86c0-47c2-a76d-2b52a0a71e7c",
"filename": "67e848e5-7fb0-480b-a1d3-f3a09d1b57f7.mp3",
"path": "uploads\\78935e75-86c0-47c2-a76d-2b52a0a71e7c\\67e848e5-7fb0-480b-a1d3-f3a09d1b57f7.mp3",
"folder": "78935e75-86c0-47c2-a76d-2b52a0a71e7c",
"info": {
"size": 12120000,
"mimetype": "audio/mp3",
"encoding": "7bit",
"originalname": "Попрошайка Евгений Владимирович из ФАСП. Выпуск 10.mp3",
"fieldname": "selectedFile"
},
"date": {
"$date": "2019-05-23T01:07:27.122Z"
}
}
],
"date": {
"$date": "2019-05-23T01:07:27.123Z"
},
"__v": 0
}
架构
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const HabalkaSchema = new Schema({
_id: {
type: String
},
files: [
{
_id: {
type: String
},
destination: {
type: String
},
filename: {
type: String
},
path: {
type: String
},
folder: {
type: String
},
info: {
size: {
type: Number
},
mimetype: {
type: String
},
encoding: {
type: String
},
originalname: {
type: String
},
fieldname: {
type: String
},
},
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Habalka = mongoose.model('habalka', HabalkaSchema);
要求
let Habalka = habalka.findOne({_id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c"});
Habalka.files.push({destination: "Harry"});
Habalka.save();
解决方案
我找到了这个解决方案和这个工作。
Habalka.findById("78935e75-86c0-47c2-a76d-2b52a0a71e7c")
.then(post => {
console.log(post)
post.files.unshift({_id: "tata", destination: "vava"});
post.save().then(res => console.log(res));
})
.catch(err => res.status(404).json({ postnotfound: 'No post found' }));
推荐阅读
- material-ui - 如何使用测试库测试 Material UI 按钮的背景颜色?
- python - 如何使用预先编写的库函数将其绘制到子图中?
- r - 如何降低正态分布曲线的高度
- flutter - Flutter bloc同时添加2个事件
- django - 按列分组 Django orm
- curl - curl 使用 -k 选项
- c++ - 由于静态值,我的程序无法执行
- python-3.x - 如何动态地将端口分配给 helm 配置?
- javascript - 在性能方面是否有 Object.assign 的替代方案
- c++ - 似乎 FlushFileBuffers() 没有设置文件结尾(因此可能导致文件损坏)