[英]save an array of objects to MongoDB with Mongoose on Javascript
[英]How to save array of objects in mongodb with mongoose?
我想保存復雜的數據,即對象數組到貓鼬。 我嘗試了幾件事,但無法保存數據。
我如上定義了我的模式,我想保存可以具有任何嵌套級別的對象數組。 架構
const mongoose = require('mongoose);
const PostSchema = new mongoose.Schema({
post: [{}]
});
let PostModel = mongoose.Model('Post', PostSchema)
這是我用來保存數據的代碼
app.post('/saveData, async (req, res) => {
const response = await Post.create(req.body);
res.json({
data: response
});
});
app.listen(8008, () => {
console.log('server running);
});
問題是我無法檢索數據。 它返回的對象數組等於已保存數組的數量,但其中沒有數據。
怎么做到呢?
這段代碼對我有用。
const PostModel = require('./Post'); //declare your model
app.post('/saveData', async (req, res) => {
const objModel = new PostModel();
objModel.post = req.body; //assign the data post array.
const response = await objModel.save();
res.json({
data: response
});
});
你的帖子模式看起來很奇怪。 您有一個 Posts 集合,然后在一個 posts 架構中,您有一個 posts 數組。 這樣做有什么意義? 帖子集合已經是帖子的“數組”。
// Perhaps you are looking for something like this.
const PostSchema = new mongoose.Schema({
title: String,
content: String,
level: Number,
footer: String,
author: ObjectId,// who wrote the post
comments: [{
user: ObjectId,
comment: String
}],
... createdAt, updatedAt etc
});
您的數據結構似乎也不符合您的架構。 例如 await Post.create({posts: req.body});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.