猫鼬推送到数组
Posted
技术标签:
【中文标题】猫鼬推送到数组【英文标题】:mongoose push to array 【发布时间】:2019-10-13 09:35:06 【问题描述】:我需要将一个对象推入一个数组到数据库中,但我得到一个错误。我究竟做错了什么 ?找到了这样一个话题Push items into mongo array via mongoose但是不能正常申请 ..................................................... ..................................................... ....................
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();
【问题讨论】:
【参考方案1】:我相信你的问题应该是files
我会试试的
habalka.update(
_id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c",
$push: files: destination: "Harry"
);
【讨论】:
让 Habalka = habalka.findOne(_id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c"); Habalka.files.push(files: destination: 'tata'); Habalka.save();我有同样的问题 habalka.update( _id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c", $push: files: destination: "Harry" );此代码没有发生错误,但没有向数据库写入任何内容。 您是在等待还是在回电?也许您可以显示实际进行更新的nodejs代码 router.post('/post', upload.single('selectedFile'), (req, res) => let habalka = new Habalka(); // 78935e75-86c0-47c2- a76d-2b52a0a71e7c habalka.update( _id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c", $push: files: destination: "Harry" ); )【参考方案2】:我找到了这个解决方案和这个工作。
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' ));
【讨论】:
以上是关于猫鼬推送到数组的主要内容,如果未能解决你的问题,请参考以下文章