简体   繁体   English

MongoError:文档验证失败 - 不知道为什么

[英]MongoError: Document failed validation - not sure why

currently working on a basic CRUD application using MongoDB as my database, and keep getting the error MongoError: Document failed validation and can't understand how to fix it.目前正在使用 MongoDB 作为我的数据库的基本 CRUD 应用程序,并不断收到错误MongoError: Document failed validation and can't understand how to fix it。

my data seems to be posting from the front-end to the express server successfully as i can see user data in the request body via some console.log statements in my server-side code.我的数据似乎已成功从前端发布到快速服务器,因为我可以通过服务器端代码中的一些 console.log 语句在请求正文中看到用户数据。

heres what i've done so far, maybe someone can spot something i've overlooked:这是我到目前为止所做的事情,也许有人可以发现我忽略的东西:

front end:前端:

// property values assigned by setter in useState hooks 
const userDetails = {
    firstName: firstName,   // john
    lastName: lastName,     // doe
    email: email,           // johndoe111@gmail.com
    password: password,     // password1
  };

  const createUserAccount = () => {
    fetch("/api/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(userDetails),
    })
      .then(console.log("POST request sucessful"))
      .catch((e) => console.log("error:", e.message));
  };

request payload:请求有效载荷:

{"firstName":"john","lastName":"doe","email":"johndoe111@gmail.com","password":"password1"}

back-end:后端:

const jsonBodyParser = bodyParser.json();

// some code to create an instance of mongo client 
// some code to connnect to my cluster


const createDatabase = async (client) => {
  const db = client.db(databaseName);

  try {
    await db.createCollection("users", {
      autoIndexId: true,
      validator: {
        $jsonSchema: {
          bsonType: "object",
          required: ["firstName", "lastName", "email", "password"],
          properties: {
            firstName: {
              bsonType: "string",
              description: "must be a string and is required",
            },
            lastName: {
              bsonType: "string",
              description: "must be a string and is required",
            },
            email: {
              bsonType: "string",
              description: "must be a string and is required",
            },
            password: {
              bsonType: "string",
              description: "must be a string and is required",
            },
          },
        },
      },
    });
    console.log("[MongoDB]: users collection created.");
    await db.createCollection("products", {});
    console.log("[MongoDB]: products collection created.");
  } catch (err) {
    console.log(err);
  }

  console.log("[MongoDB]: database created");
};


app.post("/api/users", jsonBodyParser, (req, res) => {
  console.log(req.body);
  const userDetails = {
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    password: req.body.password,
  };
  console.log("user details: ", userDetails);

  try {
    client.db(databaseName).collection("users").insertOne({ userDetails });
  } catch (error) {
    console.log("[MongoDB]: ", error);
  }
});

request body (after being parsed):请求正文(解析后):

{
  firstName: 'john',
   lastName: 'doe',
   email: 'johndoe111@gmail.com',
  password: 'password1'
 }

many thanks!非常感谢!

The problem is with this line:问题在于这一行:

client.db(databaseName).collection("users").insertOne({ userDetails })

Since userDetails is already an object, you shouldn't need the extra mustaches, just use the object directly:由于userDetails已经是 object,因此您不需要额外的胡须,直接使用 object 即可:

client.db(databaseName).collection("users").insertOne( userDetails )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongoError:无法更改文档的_id - MongoError: cannot change _id of a document 验证失败后,为什么jQuery $(document).ready()不在Rails渲染视图中触发? - Why jQuery $(document).ready() not firing inside Rails render view after failed validation(s)? 故障 - MongoError:无法连接到服务器 [未定义:27017] - Glitch - MongoError: failed to connect to server [undefined:27017] MongoError:身份验证失败。 -无法连接到MongoLab - MongoError: Authentication failed. - trouble connecting to MongoLab NodeJS Express JS-MongoError:无法连接到服务器 - NodeJS Express JS - MongoError: failed to connect to server MongoError:无法连接到服务器[localhost:27017] - MongoError: failed to connect to server [localhost:27017] 外部 Javascript 表单验证不起作用,不知道为什么? - External Javascript form validation isn't working, not sure why? MongoError:首次连接时无法连接到服务器[localhost:27017] [MongoError:连接ECONNREFU SED 127.0.0.1:27017] - MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFU SED 127.0.0.1:27017] 回调(新的 MongoError(文档)); 没有连接到 MongoDB 数据库? (节点.js) - callback(new MongoError(document)); Not connecting to MongoDB Database? (Node.js) 错误:MongoError:身份验证失败。 我正在使用 docker 和 mongoose - error: MongoError: Authentication failed. I am using docker and mongoose
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM