How to query documents in mongodb using mongoose - node.js

When i try to find a document like
const p1 = Profile.find()
console.log(p1) i should get all document in that collections but i'm getting different crap.
this is my simple schema in mongodb nodejs
const ProfileSchema = mongoose.Schema({
name: String,
age: Number,
subjects: [String],
late: Boolean
});
const Profile = mongoose.model('profile',ProfileSchema);
const profile1 = Profile.find()
console.log(profile1)

Use this -
Profile.find({}, function(err, profiles) {
console.log(profiles);
});
Refer this for more details - https://mongoosejs.com/docs/api.html#model_Model.find

const profile1 = await Profile.find({});
Since Mongoose supports async/await I would make the wrapping function async and call your find function using the await syntax.
Also make a point to pass in an empty object {} to your find function when you want to return all the documents in the collection.
More information here: https://mongoosejs.com/docs/api.html#query_Query-find

Related

Mongoose: using the Model.create() method and new Model() constructor seem to ignore parameters

I am trying to save a new document to a collection, but rather than taking the parameters from the Model() constructor or Model.create() method, an empty object is created.
I am probably doing something wrong or missing a small detail somewhere but I am currently stuck. My mongoDB database is hosted locally on mongodb for windows.
I have a schema and model:
import mongoose from 'mongoose';
const CardSchema = new mongoose.Schema({
sideA: String,
sideB: String,
})
export const CardSetSchema = new mongoose.Schema({
user_email: String,
name: String,
cards: [CardSchema],
});
const CardSet = mongoose.model('CardSet', CardSchema);
export default CardSet
I have an endpoint trying to make a new document:
.post(async (req, res) => {
const obj = { user_email: req.user_email, name: req.body.name, cards: [] };
const cardSet = new CardSet(obj);
await cardSet.save();
res.status(201).json(cardSet);
})
When looking at the data with console.log the object and cardSet look the following:
{ user_email: 'example-email#gmail.com', name: 'wa', cards: [] }
{ _id: new ObjectId("62481f4964d4b1789c3110c3") }
My connection URL looks like this:
mongodb://localhost:27017/flash-card-test
When I check MongoDB Compass the collection is indeed being populated with empty objects.
Does anyone have any idea what could be going wrong here? Many thanks!
It was a mistake. I built a model from the CardSchema rather than the CardSet schema.

Mongoose $pull not removing embedded sub-document by ObjectId [duplicate]

Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as objectId("blah").
You can do it like so:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
You can use this also
const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");
it's simplest way to do it
You can do it like this:
var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");
EDIT: New standard has fromHexString rather than fromString
Judging from the comments, you are looking for:
mongoose.mongo.BSONPure.ObjectID.isValid
Or
mongoose.Types.ObjectId.isValid
var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");
I couldn't resolve this method (admittedly I didn't search for long)
mongoose.mongo.BSONPure.ObjectID.fromHexString
If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.
You could use something like this however, which gives a bit more flex:
function toObjectId(ids) {
if (ids.constructor === Array) {
return ids.map(mongoose.Types.ObjectId);
}
return mongoose.Types.ObjectId(ids);
}
Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)
....
exports.AddSomething = (req,res,next) =>{
const newSomething = new SomeEntity({
_id:new mongoose.Types.ObjectId(), //its very own ID
somethingName:req.body.somethingName,
theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID
})
}
...
Hope it Helps
If you want to use schema
const yourSchemma = new Schema({
"customerId": {
type: mongoose.Types.ObjectId,
required: true
}
});
If you want to use ObjectId a lot and don`t want to use mongoose.types.ObjectId, you can destructure your declaration:
const {
Types: { ObjectId: ObjectId },
} = require("mongoose");
const id=ObjectId("4edd40c86762e0fb12000003")

How to access each field value in mongodb data queried using mongoose with mixed type schema

I have data in database like below. Model is defined like const Any = new Schema({ any: {} });. Now if i query const user = await Any.find({}); and try to console.log(user.name, user.email) it gives undefined. If I modify model then it is working perfectly , but I want it to be mixed type. Is there any way to do so, or I have to modify schema.
I'm using mongoose to connect to database.
{
_id: "213337867hgduhg3",
name: "some name",
email: "someone#email.com",
}
To access each properties of the first you have to use toObject method.
Taking your case, code will be like this.
const mongoose = require('mongoose');
const Any = new mongoose.Schema({});
const AnySchema = mongoose.model("collection', Any);
async function someFunction(){
const user = await AnySchema.findOne({email: 'someone#gmail.com'});
//or find() for multiple result ,
//iterate through them to get individual document
if(user){
console.log(user);
console.log('name:' + user.name);
console.log('name: ' + user.toObject().name);
}
}
Outut will be like :
{
_id: "213337867hgduhg3",
name: "some name",
email: "someone#email.com",
_v: 0
}
name: undefined
name: some name
first user.name is undefined.
To access each property use javaScript toObject method to convert it to javaScript object.

How to update a specific object in a array of objects in Node.js and Mongoose

I am new to node.js coming from java experience. I have a situation that I am trying to wrap my head around. My stack is express.js, mongoose, ejs template. Here is my scenario:
I have a schema:
var UserSchema = mongoose.Schema({
name: {
type: String,
index: true
},
password: {
type: String,
select: false
},
email: {
type: String
},
academic: [{
qualification: String,
institute: String,
from: String,
to: String,
about: String
}]
});
there is a list of academics. I want to update only one academic object in that list. How would I go about this?
router.post('/academic/schools/update', function (req, res) {
});
I pass the values from ejs template into the route and getting the values in the req.body. How would I in node and mongoose query that specific object in the route and then updates its values. I have thought about maybe adding an Id to the academic object to be able to keep track of which to update.
Each academic sub document will have an _id after you save.
There are two ways you can do it. If you pass the id of the user and id of the academic sub-doc id in the url or request body, then you can update like this:
User.findById(userId).then(user => {
let academic = user.academic.id(academicId);
academic.qualification = 'something';
return user.save();
});
If you only pass the id of the academic sub-doc, then you can do it like this:
User.findOne({'academic._id': academicId}).then(user => {
let academic = user.academic.id(academicId);
academic.qualification = 'something';
return user.save();
});
Note that sub document array return from mongoose are mongoosearray instead of the native array data type. So you can manipulate them using .id .push .pop .remove method http://mongoosejs.com/docs/subdocs.html

MongoDB find() returns nothing

I am trying to query my database from the mongodb shell to retrieve all the entries. Still, my find() method returns nothing.
This is the mongoose model that I am using:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: String,
content: String,
author: { type: String, default: 'Vlad'},
postDate: { type: Date, default: Date.now }
});
ArticleSchema.methods.formatTitle = function() {
var link = this.title.replace(/\s/g, '-');
return '/article/' + link;
};
ArticleSchema.methods.snapshot = function() {
var snapshot = this.content.substring(0, 500);
return snapshot;
};
module.exports = mongoose.model('Article', ArticleSchema);
When loading my Express.js application in the browser, I have no issues displaying all the articles that I have added using my API. Still, I just want to go inside the mongo shell and query them. I have used the following query:
// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()
I get an empty string in return, basically a new line in the console.
Your answer is right there, in the question:
// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()
So db already refers to correct database. Instead of blog, put collection name, not db name.
db.articles.find()
Mongo shell will connect when started to the test database, you will need to change the database and then execute the find on your collection :
use blog
db.articles.find()
First you choose the db, then you find on the collection.
use blog
db.articles.find()

Resources