MongoDB-错误:保存之前,文档必须具有_id [英] MongoDB - Error: document must have an _id before saving

查看:556
本文介绍了MongoDB-错误:保存之前,文档必须具有_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个项目上一直很努力.我正在跟踪一些领域中已经过时的教程,例如,他们的Jquery版本对某些功能使用了完全不同的格式,因此我不得不做很多改动.但是我认为我要解决的最后一个主要问题是我似乎找不到解决方法.在我的Schema变量中,我有_id,用户名和密码类型

I've been struggling so much with this project. I am following a tutorial that is out of date in some areas, for instance their version of Jquery used a totally different format for some functions and I had to do a lot of changing around. But I think I am down to one last major problem that I can't seem to find a fix for. In my Schema variable I've got the _id, username, and password types

var UserSchema = new mongoose.Schema({
    _id: mongoose.Schema.ObjectId,
    username: String,
    password: String
}); 

但是当我尝试向应用程序中添加新用户时,它没有弹出我应该得到的警报,而是弹出为[object Object],并且没有任何内容添加到数据库中.然后在mongo cmd中弹出此错误

but when I go to try to add a new user to my app, instead of getting the alert I am supposed to get, it pops up as [object Object] and nothing gets added to the database. Then this error pops up in the mongo cmd

错误:文档在保存之前必须具有_id".

"Error: document must have an _id before saving".

我尝试注释掉_id行,并且得到了正确的消息,但是数据库中仍然没有任何内容.

I've tried commenting out the _id line and I get the right message but still nothing shows up in my database.

推荐答案

非常简单:

  1. 如果已在架构中显式声明_id字段,则必须显式初始化
  2. 如果您尚未在架构中声明它,则MongoDB将对其进行声明和初始化.

您不能做的是将其包含在架构中,而不初始化它.它将引发您正在谈论的错误

What you can't do, is to have it in the schema but not initialize it. It will throw the error you are talking about

这篇关于MongoDB-错误:保存之前,文档必须具有_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆