MongoDB Object not getting deleted via. Mongoose - node.js

I am trying to delete a MongoDB document but it's not getting deleted
My schema is
const mongoose = require("mongoose");
const InvestorSchema = mongoose.Schema({
name: {
type: String,
index: true,
required: true
},
logoUrl: {
type: String,
required: true
},
website: {
type: String,
index: true,
unique: true,
required: true
}
});
module.exports = mongoose.model("Investor", InvestorSchema);
and I tried using these but none of them removed the document, Also i'm running on localhost with no users and roles.
// Required models
const InvestorModel = require("mongoose").model("Investor");
const deletedInvestor = InvestorModel.remove({ _id });
const deletedInvestor = InvestorModel.deleteOne({ _id });
const deletedInvestor = InvestorModel.findByIdAndRemove(_id);
const deletedInvestor = InvestorModel.findOneAndRemove({_id});
const deletedInvestor = InvestorModel.findByIdAndDelete(_id);
const deletedInvestor = InvestorModel.findOneAndDelete({_id});
How do i solve this?

try {
InvestorModel.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
} catch (e) {
console.log(e);
}

here the problem is you don't specify what object from the collection you want to remove...
So you should use your code implementation like this mate
InvestorModel.remove({ _id: '563237a41a4d68582c2509da' },callback);
InvestorModel.deleteOne({_id: '563237a41a4d68582c2509da' },callback);
InvestorModel.findByIdAndRemove({_id: '563237a41a4d68582c2509da'},callback);

Related

Node Js MongoDb Error "ERR_INVALID_ARG_TYPE"

i am beginner of node js and mongodb.when i tried to add the add via postman to mongodb i ran into the problem.
{
"code": "ERR_INVALID_ARG_TYPE"
}
what i tried so far i attached below.
routes
router.route('/user/getAll').get(userController.getDataConntrollerfn);
userController.js
var createUserControllerFn = async (req, res) =>
{
const userModelData = new userModel(req.body)
try
{
await userModelData.save()
res.status(201).send(userModel);
}
catch(error)
{
res.status(400).send(error);
}
}
userModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: {
type: String,
required: true
},
address: {
type: String,
required: true
},
phone: {
type: String,
required: true
}
});
module.exports = mongoose.model('employees', userSchema);

Product not updating - Mongoose MongoDB

I am unable to update and save a change in the database using mongoose. I am getting the same value for foundProduct twice when I console.log. What could be going wrong?
// Schema
const productSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
onSale: {
type: Boolean,
default: false,
},
}
)
// model
const Product = mongoose.model('Product', productSchema)
const findProduct = async () => {
const foundProduct = await Product.findOne({ name: 'Mountain Bike' });
console.log(foundProduct)
foundProduct.OnSale = true;
await foundProduct.save().then((data) => console.log(data))
// console.log(foundProduct)
}
findProduct();
You have a typo. Change foundProduct.OnSale = true; with foundProduct.onSale = true;.
Since you are using the wrong case, Mongoose considers OnSale to be an extra field. And because it's not in your schema, it's ignored when saving to db.
You have a typo error in the foundProduct.OnSale instead of foundProduct.onSale

Facing issues with MongoDB Bulk API while trying to upload my JSON file to MongoDB using NodeJS

I've been trying to sequentially upload my json file to MongoDB using the Bulk API. But everytime I try to do so I receive the following error "TypeError: bulk.insert is not a function"
I've referenced the docs and my syntax looks alright. Do let me know how I can go about fixing the same.
Below is my code snippet.
productRouter.js
const products = require('../models/product');
productRouter.route('/bulkupload')
.get((req,res,next) => {
var productJson = fs.readFileSync('development/mongodb-file-import.json');
productJson = JSON.parse(productJson);
console.log(productJson[1])
var bulk = products.collection.initializeOrderedBulkOp();
for (i=0; i < productJson.length; i+=1) {
bulk.insert(productJson[i])
}
bulk.execute(function (errx) {
if (errx) {
return next(errx);
}
console.log('Success');
});
})
EDIT
app.js
const mongoose = require('mongoose');
const product = require('./models/product');
const warehouse = require('./models/warehouse');
const url = process.env.MONGODB_URL_ATLAS;
const connect = mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
connect.then((db) => {
winston.info('Connected correctly to server');
}, (err) => {winston.error(err); });
product.js
const mongoose = require('mongoose');
const shortId = require('shortid');
const Schema = mongoose.Schema;
const productSchema = new Schema({
productName: {
type: String,
required: true,
required: 'Please choose the product from the list!'
},
productUnit: {
type: String,
required: true
},
productPricePerUnit: {
type: Number,
required: true
},
productSku: {
type: String,
required: true,
uppercase: 1,
index: {
unique: true
},
default: "SNS" + shortId.generate()
}
},{
timestamps: true
});
var products = mongoose.model('products', productSchema);
module.exports = products;
I think you can do it with this code below:
productRouter.route('/bulkupload')
.get(async(req, res, next) => {
var products = fs.readFileSync('development/mongodb-file-import.json');
products = JSON.parse(products);
const jobQuerys = [];
products.forEach(p => {
p.productSku = p.productSku ? p.productSku : "SNS" + shortId.generate();
const product = new Product(p);
jobQuerys.push(product.save());
});
const result = await Promise.all(jobQuerys);
console.log(result);
});
I hope it can help you.

I can't handle populate in mongoose

I think it's not populating categories couse when i try log 'category' in console i get
"ReferenceError: category is not defined". For me it is like in docs but as we see it's not. Is anyone can tell me what is wrong??
//model/Category.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CatSchema = new Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
}
});
mongoose.model("categories", CatSchema, "categories");
model/Story.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const StorySchema = new Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
category: {
type: Schema.Types.ObjectId,
ref: "categories"
}
});
mongoose.model("stories", StorySchema, "stories");
routes/stories.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Category = mongoose.model('categories');
const Story = mongoose.model('stories');
router.get('/add', (req, res) => {
Story.find()
.populate('category', 'title')
.then(stories => {
res.render('stories/add', {
stories: stories
});
});
});
Query.prototype.populate() returns a Query object on which you need to run .exec(), try this:
Story.find({})
.populate('category', 'title')
.exec()
.then(stories => {
res.render('stories/add', {
stories: stories
});
});
It was problem with that how I want to use it. Code is working

Mongoose one-to-many

can you explain me how to organize mongoose models to create one to many connections? It is needed keep separate collections.
suppose i have stores and items
//store.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Store', {
name : String,
itemsinstore: [ String]
});
//item.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Item', {
name : String,
storeforitem: [String]
});
Am i doing it in the right way?
And how to access pass data to arryas?
Here is the code yo enter name to item. But how to enter id to array of id's (itemsinstore)?
app.post('/api/stores', function(req, res) {
Store.create({
name: req.body.name,
}, function(err, store) {
if (err)
res.send(err);
});
})
You should use model reference and populate() method:
http://mongoosejs.com/docs/populate.html
Define your models:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var storeSchema = Schema({
name : String,
itemsInStore: [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});
var Store = mongoose.model('Store', storeSchema);
var itemSchema = Schema({
name : String,
storeForItem: [{ type: Schema.Types.ObjectId, ref: 'Store' }]
});
var Item = mongoose.model('Item', itemSchema);
Save a new item into an existing store:
var item = new Item({name: 'Foo'});
item.save(function(err) {
store.itemsInStore.push(item);
store.save(function(err) {
// todo
});
});
Get items from a store
Store
.find({}) // all
.populate('itemsInStore')
.exec(function (err, stores) {
if (err) return handleError(err);
// Stores with items
});
You can do using the best practices with Virtuals.
Store.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const StoreSchema = new Schema({
name: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
})
StoreSchema.virtual('items', {
ref: 'Item',
localField: '_id',
foreignField: 'storeId',
justOne: false // set true for one-to-one relationship
})
module.exports = mongoose.model('Store', StoreSchema)
Item.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ItemSchema = new Schema({
storeId: {
type: Schema.Types.ObjectId,
required: true
},
name: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Item', ItemSchema)
StoreController.js
const Store = require('Store.js')
module.exports.getStore = (req, res) => {
const query = Store.findById(req.params.id).populate('items')
query.exec((err, store) => {
return res.status(200).json({ store, items: store.items })
})
}
Keep in mind that virtuals are not included in toJSON() output by default. If you want populate virtuals to show up when using functions that rely on JSON.stringify(), like Express' res.json() function, set the virtuals: true option on your schema's toJSON options.
// Set `virtuals: true` so `res.json()` works
const StoreSchema = new Schema({
name: String
}, { toJSON: { virtuals: true } });
Okay, this is how you define a dependancy:
var mongoose = require('mongoose');
module.exports = mongoose.model('Todo', {
name : String,
itemsinstore: [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});
And make sure you have different names:
var mongoose = require('mongoose');
module.exports = mongoose.model('Item', {
name : String,
storeforitem: [String]
});
Keep an eye on Item in both cases.
And then you just want to pass the array of ObjectIDs in it. See more here: http://mongoosejs.com/docs/populate.html
Try this:
Store.findOne({_id:'5892b603986f7a419c1add07'})
.exec (function(err, store){
if(err) return res.send(err);
var item = new Item({name: 'Foo'});
item.save(function(err) {
store.itemsInStore.push(item);
store.save(function(err) {
// todo
});
});

Resources