MongoDB不会保存数组数据

gblwokeq  于 2023-04-11  发布在  Go
关注(0)|答案(1)|浏览(157)

我试图使用Mongoose将存储在另一个变量中的字符串数组保存到MongoDB数据库中。
架构:

const mongoose = require("mongoose");

const schema = new mongoose.Schema({
    _id: String,
    user: String,
    guild: String,
    content: String,
    attachment: String,
    messages: String
})

module.exports = mongoose.model("messages", schema, "messages")

我的代码:

const messageSchema = require("../models/messageSchema");

const messages = ["array", "of", "strings"];

// Save Data
const data = new messageSchema({
    _id: "1234567890",
    user: "1234567890",
    guild: "1234567890",
    content: "Hello World",
    attachment: null,
    messages: messages
})

await data.save();

它保存了除了消息数组之外的所有数据。对于消息,它只是一个空数组。我在控制台也没有得到任何错误。
我尝试使用for循环从messages数组推送到一个数组,但也不起作用。

const messages = ["array", "of", "strings"];

let data = new messageSchema({
    _id: "1234567890",
    user: "1234567890",
    guild: "1234567890",
    content: "Hello World",
    attachment: null,
    messages: []
})

for(const msg of messages) {
    data.messages.push(msg);
}

我还尝试了在schema中定义数组的不同方法,如:

messages: [String]
messages: [{ type: String }]
xbp102n0

xbp102n01#

像这样更改您的模式

const mongoose = require("mongoose");
const schema = new mongoose.Schema({
 _id: String,
 user: String,
 guild: String,
 content: String,
 attachment: String,
 messages: mongoose.Schema.Types.Mixed   
},{ strict: false } )

module.exports = mongoose.model("messages", schema)

我希望这能解决你的问题

相关问题