Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Got error on blog.js when inserting documents (Section 26/ Insert Documents) #17

Open
m-tonon opened this issue Nov 19, 2022 · 2 comments

Comments

@m-tonon
Copy link

m-tonon commented Nov 19, 2022

I was getting this error:

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
    at new BSONTypeError (/home/mtonon/Web Dev/mongodb-page/node_modules/bson/lib/error.js:41:28)
    **at new ObjectId** (/home/mtonon/Web Dev/mongodb-page/node_modules/bson/lib/objectid.js:67:23)
    at /home/mtonon/Web Dev/mongodb-page/routes/blog.js:28:20

Then I found a solution on forums, just use .trim() on const authorId to remove any extra blank space:

router.post('/posts', async function(req,res){
  const authorId = new ObjectId(req.body.author.trim()); 

If someone is getting the same error, this worked for me!

@m-tonon m-tonon closed this as completed Nov 19, 2022
@m-tonon m-tonon reopened this Nov 19, 2022
@IanPaniagua
Copy link

Is not working for me

@IanPaniagua
Copy link

const express = require('express');

const mongodb = require('mongodb');
const db = require('../data/database');

const ObjectId = mongodb.ObjectId;

const router = express.Router();

router.get('/',function(req, res) {

res.redirect('/posts');
});

router.get('/posts', function(req, res) {
res.render('posts-list');
});

router.get('/new-post', async function(req, res) {
//Establish acces to the table authors
const authors = await db.getDb().collection('authors').find().toArray();
console.log(authors);
res.render('create-post', {authors:authors});
});

router.post('/posts', async function(req, res) {
// const authorId = new ObjectId(req.body.author);
const authorId = new ObjectId(req.body.author.trim());

const author = await db.getDb().collection('authors').findOne({_id: authorId})
const newPost = {
title: req.body.title,
summary: req.body.summary,
body: req.body.content,
date: new Date(),
author: {
id: author,
name: author.name,
email: author.email
}
};
const result = db.getDb().collection('posts').insertOne(newPost);
console.log(result);
res.redirect('/posts');

});

module.exports = router;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants