首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >猫鼬文档_id是空的,所以当我尝试保存时,我得到MongooseError:文档必须在保存之前具有和id。

猫鼬文档_id是空的,所以当我尝试保存时,我得到MongooseError:文档必须在保存之前具有和id。
EN

Stack Overflow用户
提问于 2022-06-22 14:59:50
回答 2查看 186关注 0票数 0

我在制造一个不和谐的机器人从亚马逊那里刮价格。我使用一个mongoDB数据库来存储用户给机器人的链接,以跟踪链接导致的项目的价格。

我的问题是当我运行我的代码并使用add命令时,我的控制台读取.

代码语言:javascript
复制
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

我读过医生的文章,我的理解是猫鼬会自动生成一个唯一的id。我知道您可以覆盖这个在您的模式中定义id,但是我还没有这样做,所以我不知道为什么console.log(a)输出null,而.save()出错。

我的add.js文件

代码语言:javascript
复制
//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文件

代码语言:javascript
复制
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);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-06-22 16:31:35

当创建一个新的模式时,选项必须在同一对大括号内,但是在更新时,它是独立的,因为您正在更改多个元素。

这就是错误发生的原因。您已经共享了一段工作代码,所以我猜您已经不需要了。

票数 1
EN

Stack Overflow用户

发布于 2022-06-22 16:14:37

所以我发现了我的问题。我换了这条线

代码语言:javascript
复制
var newLink = new Link({ user: user }, { link: URL }, { price: "N/A" })

代码语言:javascript
复制
const newLink = new Link({ user: user, link: URL, price: "N/A" });

我不知道为什么要修复它,我不认为这是因为我更改了var -> const,并且查看文档,我认为第一行是正确的方法。

我最初从文档中使用的行

代码语言:javascript
复制
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
});

这是文档中的错误吗?还是一个可能的窃听器?无论哪种方式,这个问题现在都得到了解决。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72717833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档