How to define an objectId type in mongoose 6.0.0^
I am seeing many answers saying that the correct way to define an objectId type in a mongoose schema is like:
type: mongoose.Schema.Types.ObjectId
But from the mongoose docs they show that you can define an objectId type like so:
const carSchema = new mongoose.Schema({ driver: mongoose.ObjectId });
Is there something I am missing? What is the correct way to define an objectId type? Are both methods correct or one is outdated?
1 answer
-
answered 2022-01-25 14:34
Alex Blex
Both of these roads lead to Rome, there is no single "correct" way.
The type is defined in https://github.com/Automattic/mongoose/blob/master/lib/schema/index.js#L24 as
exports.ObjectId = require('./objectid');
The rest are the pointers to this export. Some are shorter, some are longer unless you use them in the context.
The
mongoose.Schema.Types.ObjectId
comes from there: https://github.com/Automattic/mongoose/blob/master/lib/schema.jsSchema.Types = MongooseTypes = require('./schema/index');
mongoose.ObjectId
comes from https://github.com/Automattic/mongoose/blob/master/lib/index.js#L940Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;
do you know?
how many words do you know
See also questions close to this topic
-
Error message : MongoServerError: bad auth :Authentication failed
What is the reason behind this error? this code I am using to connect to DB.
const uri =`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.xft2s.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
-
In Mongo, If a document I'm saving "Prateek" then I don't want on the next create operation even the "prateek" or "praTEEK", etc is saved
//** If I'm adding a new document with the name: "India", then I don't want that the DB allow another name with the name: "INDIA", "india", "indIA", etc. I'm new and learning, help would be great!!**
// Controller
var Dinosaur = require('../models/dinosaurs'); //addDino module.exports.addDino = (req, res) => { var name = req.body.name; var type = req.body.type; var height = req.body.height; var weight = req.body.weight; var Period = req.body.Period; req.checkBody('name', 'Name is required').notEmpty(); var errors = req.validationErrors(); if (errors) return res.status(400).send({ message: 'Name is Required' }); else { let newDino = { name: name, type: type, height: height, weight: weight, Period: Period } Dinosaur.addDino(newDino, (err, result) => { if (err) { if (err.name) return res.status(409).send({ message: name + ' Already Exist' }); else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url }); else return res.json(err, "Server Error"); } else { return res.status(200).send({ message: "Done" }); } }); } }
// Model
var mongoose = require('mongoose'); //dinosaur schema var DinosaurSchema = mongoose.Schema({ name: { type: String, unique: true }, type: { type: String }, height: { type: Number }, weight: { type: Number }, Period: { type: String } }); var Dinosaur = mongoose.model('dinosaur', DinosaurSchema); //add module.exports.addDino = (query, callback) => { Dinosaur.create(query, callback); }
// GetAll, Already Created a new document with the name "Brachiosaurus"
// > Create, a new create with the first letter lower case "brachiosaurus", Don't want it to be pushed.
- i am trying to run the node of ganache but getting this error
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
Unexpected token ')' in D:\Mridul\Codes\js\API BASED\Anime Quote\views\info.ejs while compiling ejs
So I want to display MongoDB data in HTML so I used the EJS template but this is the error it is showing . I can't seem to figure out where the problem is, IS it in the EJS file or in the data?
Here is the EJS template
` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Information</title> </head> <body> <h1>Information</h1> <ul class="savage"> <%Content.forEach(data=>{%> <p><%=data.Name%></p> <p><%=data.Description%></p> <p><%=data.Birthday%></p> <p><%=data.Alternative_Name%></p> <p><%=data.Backstory%></p> <p><%=data.Anime_OR_Manga>%></p> <%})%> </ul> <h2>Add a Info</h2> </body>`
Here is the server.js
const express=require('express'); const cors=require('cors'); const app= express(); const PORT =8000; let ejs=require('ejs'); const mongoose=require('mongoose'); app.set('view engine','ejs'); const uri="mongodb+srv://mridultiwar:mridultiwari@cluster0.ub68a.mongodb.net/SearchBAckend?retryWrites=true&w=majority"; mongoose.connect(uri); const savageSchema=new mongoose.Schema({ Name:String, Description:String, Birthday:String, Alternative_Name:String, Backstory:String, Anime_OR_Manga:String, }) const Savage=mongoose.model('savages',savageSchema) // const client=new MongoClient(uri) // MongoClient.connect(uri); //let content=document.getElementById('addedinfo'); // app.get('/view',function(req,res){ // db.serialize(()=>{ // db.run() // }) // }); app.get('/info',function(req,res){ Savage.findOne({},'Izuku', function(err,data){ console.log(data); res.render('info.ejs',{ Content:data }) }) })
And here is the data i wanna retrieve
{"_id":{"$oid":"6275e6402c1944072bcb4646"}, "Name":"Izuku", "Description":"Izuku 'Deku' Midoriya is the main protagonist of the manga and anime My Hero Academia and is in Class 1-A at U.A. High School." ,"Birthday":"July 15,2010 Cancer", "Alternative_Name":"Deku", "Backstory":"In a world where most humans on the planet develop superpowers soon after they're born, a boy named Izuku Midoriya was one of the few who never developed any powers. As a child, Izuku dreamed to become a superhero like his idol, All Might, after he developed his power, or 'Quirk'. As such, he was devastated once he learned that he'd never get a quirk. His lack of a Quirk made him a prime target for bullying, but Izuku still wanted to be a hero, and planned to go to the prestigious U.A. hero academy. Ten months before the entrance exams for U.A. started, Izuku came face to face with All Might after he was saved from a villain by him. Izuku asked All Might if it was possible for someone without a quirk to be a hero, but he responded by telling him that he needed realistic dreams. Soon after, the same villain from before ended up breaking free and attacking one of Izuku classmates. Despite not having a quirk, Izuku still tried to save his classmate. While he didn't stop the villain, he did give All Might enough time to defeat them himself. After this, All Might decided that Izuku had the potential to become a hero, with his help. He decided that he would grant Izuku his own Quirk to help him achieve his dreams. After ten months of training, All Might passed his Quirk, One For All, down to Izuku. Izuku then managed to pass the entrance exam, and officially enrolled in U.A, taking on the Hero name 'Deku", "Anime_OR_Manga": "Boku No Hero Academia"
I tried looking for the similar error in stack overflow, but i can't seem to find it Here is the error shown:
{ _id: new ObjectId("626e9ade4b9416e659a5f4e1") } SyntaxError: Unexpected token ')' in D:\Mridul\Codes\js\API BASED\Anime Quote\views\info.ejs while compiling ejs If the above error is not helpful, you may want to try EJS-Lint: https://github.com/RyanZim/EJS-Lint Or, if you meant to create an async function, pass `async: true` as an option. at new Function (<anonymous>) at Template.compile (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:673:12) at Object.compile (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:398:16) at handleCache (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:235:18) at tryHandleCache (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:274:16) at View.exports.renderFile [as engine] (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:491:10) at View.render (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\view.js:135:8) at tryRender (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\application.js:640:10) at Function.render (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\application.js:592:3) at ServerResponse.render (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\response.js:1017:7)
-
mongoose save internal documents creating a document that contains a document
Im learning mongoose and i have a question how to save several documents:
// Product.js const categorySchema = mongoose.Schema( { name: String }, { collection: "categories" } ); const productSchema = mongoose.Schema( { name: String, category: categorySchema }, { collection: "products" } ); modules.exports = mongoose.model("Product", productSchema);
The idea is that when I create a product this way
const Product = require("./Product.js") const product = new Product({name: 'Soccer Ball', category: {name: "Sports"}) await product.save()
i want to get a document in the collection products and also a document in the collection categories
how can it be possible
thanks in advance
PD : Im getting this but category is not save in the collection
{ "msg": "Product created succesfully", "ok": true, "product": { "name": "Soccer ball", "category": { "name": "Sports", "_id": "6275df4c8149967bea21e7c0" }, "_id": "6275df4c8149967bea21e7bf", "__v": 0 } }
-
Mongoose findByIdAndUpdate - not updating selection
I'm following a tutorial with MERN (source code here: https://github.com/Nikhilthadani/Book-Store-With-MERN-Stack/blob/Backend/controllers/books-controller.js)
Everything seems fine with the initial routing (get & post) , until we added a route for updating entries (PUT) in mongoDB.
Here is my function for the PUT
//book-controller.js const updateBook = async (req, res, next) => { const id = req.params.id; const { name, code } = req.body; let book; try { book = await Book.findByIdAndUpdate(id, {new: true}, { name, code, }); book = await book.save(); } catch (err) { console.log(err); } if (!book) { return res.status(404).json({ message: "Unable To Update By this ID" }); } return res.status(200).json({ book }); };
Here is my Schema
// Book.js const mongoose = require('mongoose') const bookSchema = new mongoose.Schema({ name: { type: String, required: true, }, code: { type: Number, required: true, }, }); module.exports = mongoose.model("Book", bookSchema);
When I try to test this function in Postman, the GET request returns the entry that I'm attempting to update just fine.
Confirming database entry with Get
However, after testing PUT, the particular entry I'm trying to update will remain unchanged, despite no output errors