簡體   English   中英

Mongoose 文檔 _id 為空,所以當我嘗試保存時,我得到 MongooseError: document must have and id before save

[英]Mongoose document _id is null, so when I try to save I get MongooseError: document must have and id before saving

我正在制作一個不和諧的機器人來從亞馬遜上刮價格。 我使用 mongoDB 數據庫來存儲用戶提供給機器人的鏈接,以跟蹤鏈接指向的商品的價格。

我的問題是當我運行代碼並使用 add 命令時,我的控制台顯示...

Starting...
Online! Logged in as Amazon Price Tracker#6927
Connected to Database
null
MongooseError: document must have an _id before saving
    at C:\Users\logic\Documents\Disc Bot\node_modules\mongoose\lib\model.js:291:18
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
Disconnected from Database

我已經閱讀了文檔,我的理解是 mongoose 會自動生成一個唯一的 ID。 我知道你可以覆蓋這個我在你的模式中定義一個 id,但我沒有這樣做,所以我不知道為什么 console.log(a) 打印 null,並且 .save() 錯誤。

我的 add.js 文件

//add function using mongoose for mongodb
const { SlashCommandBuilder } = require("@discordjs/builders");

const mongoose = require("mongoose");
const { MongoDBurl } = require("../config.json");
const Link = require("../Schemas/Link.js");

module.exports = {
    //Build the slash command
    data: new SlashCommandBuilder()
    .setName("add")
    .setDescription("add a url to watch list")
    .addStringOption(option =>
        option.setName("url")
            .setDescription("url to add to watch list")
            .setRequired(true),
        ),

    //Function that runs when the command is used
    async execute (interaction) {
        const URL = interaction.options.getString("url");
        const user = interaction.user.username;

        await interaction.reply(`On it! Adding ${URL} to your watch list`)

        //Connect to the database, throws an error if it can't connect
        await mongoose.connect(MongoDBurl)
            .then( () => console.log("Connected to Database"))
            .catch(err => console.log(err));

        //Check if the link is already in the database
        var exists = await Link.exists({ link: URL}).exec()
                    .catch(err => console.log(err))

        if (exists) {
            console.log("This Document Already Exists")
            interaction.editReply(`Oops! That link is already in my database.`)
        } else {
            //If the link dosen't exist, create a document and save it to the database
            var newLink = new Link({ user: user }, { link: URL }, { price: "N/A" })
            // Debuging variable
            var a = newLink.id;
            console.log(a)

            await newLink.save()
                .then( () => {
                    console.log("Document Saved")
                    interaction.editReply(`All done! I have saved ${URL} to your watch list.`)
                })
                .catch(err => {
                    console.log(err)
                    interaction.editReply("Oops! Something went wrong, I wasen't able to save this link.")
                })
        }

        //Close the connection when we finish
        await mongoose.connection.close()
            .then( () => console.log("Disconnected from Database"))
    }
};

我的 Link.js 文件

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const LinkSchema = new Schema({
    user: {
        type: String,
        requiered: true
    },
    link: {
        type: String,
        requiered: true
    },
    price: {
        type: String,
        requiered: true
    },
})

module.exports = mongoose.model("Link", LinkSchema);

所以我發現了我的問題。 我改變了這條線

var newLink = new Link({ user: user }, { link: URL }, { price: "N/A" })

const newLink = new Link({ user: user, link: URL, price: "N/A" });

我不知道為什么要修復它,我不認為這是因為我更改了 var -> const,並且查看文檔我認為第一行是正確的方法

我最初從文檔中使用的行

Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) {
  // Updated at most one doc, `res.nModified` contains the number
  // of docs that MongoDB updated
});

這是文檔中的錯誤嗎? 還是一個可能的錯誤? 無論哪種方式,問題現在都已解決。

創建新模式時,選項必須在同一對花括號內,但是在更新時,它是分開的,因為您要更改多個元素。

這就是發生錯誤的原因。 您已經共享了一段工作代碼,所以我猜您不再需要一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM