Saving documents on mongoose on console app keep hanging the execution - node.js

I have a fairly simple nodejs console app using mongoose, and I am trying to save a document and end the program execution. The problem is that it hangs in a waiting state.
I just found some other questions like this, informing things like trying to close the connection, but I had no luck with the responses. I already tried everything that I found on docs, and answers and nothing worked.
My code is pretty straightforward:
const mongoose = require("mongoose");
let personSchema = new mongoose.Schema(
{
name: {type: String},
age: {type: Number}
},
{ collection: "person" }
);
let personModel = mongoose.model("Person", personSchema);
mongoose.connect("mongodb://localhost:27017/People", {useNewUrlParser: true, useUnifiedTopology: true}).then(
() => {
personModel.create({
name: "Alex",
age: 40
});
},
err => {
console.error("Error", err);
}
);
What I already tried:
Close the connection after create. Results on the error: Topology is closed. Please connect.
Setting keepAlive to false: no effect
Setting bufferCommands to false: no effect
Is there a way to fix this behavior? Any ideas?

Related

Unable to Connect to the MongoDB Database

Using the MongoDb and Mongoose for the first time to store the data of my app.js file. When I run the app.js then it throws this error after a while -> MongooseError: Operation peoples.insertOne() buffering timed out after 10000ms.
import mongoose from "mongoose";
mongoose.set("strictQuery", false);
mongoose.connect(
"mongodb://localhost:27017/peopleDB",
{ useNewUrlParser: true },
(err) => {
if (err) console.log(err);
else console.log("MongoDB is connected");
}
);
const peopleSchema = new mongoose.Schema({
name: String,
age: Number,
});
const People = new mongoose.model("People", peopleSchema);
const people = new People({ name: "John", age: 37 });
people.save();
this is the code that I wrote
After a lot of searching for the solution got to know that the connection was not made, if you are using the node the latest node.js version then replace the "localhost" with "127.0.0.1" and then try running the app.js
Create model name as "person", since people is already plural, and it may cause an error.
And make sure you run mongod server in the background using git

Can't upload a document to my mongoDB server

I am studying on my own node.js and I am following codewithmosh website.
The thing is, is that I try to upload a new object to my mongo database using compass.
I have the following code (see screenshots for outputs) and there is no error and on mosh'es tutorial everything is working great.
The problem I have is that my server isn't being updated with the new document.
Any idea what I am missing?
I refreshed the compass a few times and nothing changes.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true , useUnifiedTopology: true}).then(() =>
console.log('connected to MongoDB')
).catch((err) => console / log('Could not connect to MongoDB', err));
const courseSchema = new mongoose.Schema({
name: String,
author:String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean
})
const Course = mongoose.model('Course', courseSchema);
async function createCourse () {
const course = new Course ({
name: 'node.js Course',
author: 'Daniel',
tags: ['node', 'backend'],
isPublished: true,
});
const result = await course.save();
console.log(result);
}
createCourse();
OK I figure it out.
There was a bad configuration in my compass.
I had to go to setup a connection

How to fix and prevent duplicate key error in mongodb

I've been working on a hobby project recently and I've encountered a problem I can't seem to figure out, even after scouring the internet for an answer. I'm using Node.js on c9.io with MongoDB. Anytime I try to create a new entry into the database, the first entry works and goes through fine, but then the second one causes an error.
E11000 duplicate key error collection: project.tasks index: username_1 dup key:
{ : null }'
My Schema:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var taskSchema = new mongoose.Schema({
task: String,
region: String,
cost: String,
when: String,
isAccepted: Boolean,
author: {
id:{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
},
tasker: {
id : {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
}
});
taskSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Task", taskSchema);
My Post Request:
app.post("/taskers/index/show", function(req, res){
var task = req.body.task;
var newTask = {
task: task.task,
region: task.region,
cost: task.cost,
when: task.when,
isAccepted: false,
author: req.user._id,
tasker: req.user._id
};
console.log("STSOTSOTSOTOOPP");
Task.create(newTask, function(err, newlyCreated){
if(err){
console.log(err);
} else {
console.log(newlyCreated);
res.redirect("/users/index");
}
});
});
If anyone knows what I'm doing wrong or can lead me to a solution, that would be amazing as I've been stuck on this for a while.
E11000 duplicate key error collection: project.tasks index: username_1 dup key: { : null }
This error is coming from mongo (not from mongoose). Removing indexes from your mongoose schema will not have any impact on the underlying collection so you'll now want to remove the unique index on username from your tasks collection.
This index was likely created by previous code that we no longer see (or perhaps by that taskSchema.plugin(passportLocalMongoose); -- that sounds suspiciously like the kind of thing that would want an index on username).
If you connect to mongo using the shell, you should be to run db.tasks.getIndexes() to see that unique username index, and then use the dropIndexCommand to remove the offending index.
See E11000 duplicate key error index in mongodb mongoose for more details about how mongoose & mongo interact.
Open MongoDB compass and connect same Database that you are using in your code,
open your Db and select your collection in MongoDB Compass
navigate to indexes section and remove unnecessary index
save

Mongoose Validate Not Called

I'm following the mongoose documentation out of the book and I cannot get even the most simple validator to work. What am I missing? This validator which I assume would fail 100% succeeds 100% and I can insert any userid I want. In this I am simply trying to see if it's called and insertion always passes when I expect it to fail. I have tried many variations and examples I've seen online and in all cases the validator seem not to be called.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const profileSchema = new Schema({
created: {
type: Date,
default: Date.now
},
userid: {
type: Schema.Types.ObjectId,
ref: 'user',
validate: {
validator: val => { return false; },
message: 'something'
}
});
const Profile = mongoose.model('profile',profileSchema);
This is a known issue during update. I didn't recognize the way I had my code structured that I was doing an update. I had an 'add' function which called findOneAndUpdate(). Thanks for the good questions which helped me find my problem.
See the answer:
Mongoose .update() does not trigger validation checking

Node Mongoose - saving embedded documents on API once receiving mongoId

I would like to know the best approach to solve the current scenario.
I've got a node API which uses mongoose and bluebird. And some Android clients will post "movement" entities to it.
(Question at the end).
Let's say movement-model.js exports the Schema, and looks like this:
"use strict";
const mongoose = require('mongoose');
const _movementSchema = {
movementId: { type: Number, requried: true },
relMovementId: Number,
_party: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Party' }
}
module.exports = mongoose.Schema(_movementSchema, {collection: 'movement'});
And related exported Schema on party-model.js is as follows:
"use strict";
const mongoose = require('mongoose');
const _partySchema = {
active: { type: Boolean, default: true },
name: { type: String, trim: true, required: true },
logo: { type: Buffer },
coordenates: { lat: Number, long: Number },
startOn: { type: Date, required: true },
endOn: { type: Date, required: true }
}
module.exports = mongoose.Schema(_partySchema, {collection: 'party'});
Android client would send the JSON with ObjectId and not full populated object. So when the POST comes, I'm using it directly (i.e: let _movement = req.body;) and on the movement-dao.js I've got the createNew method and I'm exporting the Model:
"use strict";
const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.Promise = Promise;
const movementSchema = require('../model/movement-model');
movementSchema.statics.createNew = (movement) => {
return new Promise((resolve, reject) => {
if (!_.isObject(movement)) {
return reject(new TypeError('Movement is not a valid object.'));
}
let _something = new Movement(movement);
_something.save((err, saved) => {
err ? reject(err)
: resolve(saved);
});
});
}
const Movement = mongoose.model('Movement', movementSchema);
module.exports = Movement;
What I want to accomplish is to: save the movement collection with the _party as the full party document is at the moment of the save, I mean an embedded document of a copy of the Party document, which will not be affected by the updates done to the Party document in the future.
While I cannot change the Android Client, so I will still be getting only the ObjectId from it.
JSON example of what Android client will post: {"movementId":1, "relMovementId":4138, "_party":"58dbfe26194cfc5a9ec9b7c5"}
I'm confused now, and not sure if due to the way Android is posting the JSON, I need two schemas; one for the object received (i.e: with ObjectId and ref to Party) and a second one for the object persisted (i.e: with the schema referenced _party: Party.Schema) or if I could do something simpler as some populate prior to save... or what.
For the sake of closing this up:
I've implemented one of the approaches I had in mind while writing the question. Movement schema changed so that: _party: Party.Schema
When I get a POST to create a new movement I do a getById and use the result of that exec to populate the value as an embedded doc.

Resources