Is it possible push into an array in a mongoDB schema.
For example in the following schema:
var ProviderSchema = new Schema({
keyWords: [String]
});
How can I push data into the keyWords using the route below:
app.put('/providers/words/:provider_id', function(req, res) {
// Push to array here
})
Thank you in advance.
Something like this:
app.put('/providers/words/:provider_id', function(req, res) {
var id = req.params('provider_id');
var update = {$push: {"keyWords": "keyword"}}; // Push a keyword into the model array.
ProviderSchema.findOneAndUpdate(id, update, function(err, provider){
if(err) return err;
});
});
Related
Why I can't remove record by _id?
Code:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
You need to pass the _id value as an ObjectID, not a string:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')});
});
MongoDb has now marked the remove method as deprecated. It has been replaced by two separate methods: deleteOne and deleteMany.
Here is their relevant getting started guide: https://docs.mongodb.org/getting-started/node/remove/
and here is a quick sample:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')}, function(err, results) {
if (err){
console.log("failed");
throw err;
}
console.log("success");
});
});
With TypeScript, you can to it using imports, instead of requiring the whole library
import { ObjectID } from 'mongodb'
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new ObjectID('4d512b45cc9374271b00000f')});
});
First include mongodb
var mongodb = require("mongodb");
You have to include the ObjectID from mongodb
var ObjectID = require('mongodb').ObjectID;
Then Use
var delete_id = request.params.id;//your id
collection.deleteOne({_id: new mongodb.ObjectID(delete_id.toString())});
1000% works...
i think we have to require mongodb as const
and use it with mongodb
I recently stumbled with this problem today and I find that the fix is:
const mongodb = require('mongodb');
const ObjectID = require('mongodb').ObjectID;
databaseName.collectionName.deleteOne({_id: new mongodb.ObjectID(id)} , (err)=>{
if (err) throw err;
console.log('Deleted'+id);
});
I am working on a ExpressJS and MongoDB project that involves parsing dynamic mongoose schema. The way I set up the dynamic schema is and parse it :
Step-1
//Creating a mongoose schema
var userSchema = mongoose.Schema({
measurements : [
mongoose.Schema({
time: String
})
]});
Step-2
//Creating a mongoose model for the schema
var User = mongoose.model('User', userSchema);
var user = new User();
user.measurements = [{time:req.body.time}]
//save the info
user.save(function(err) {
if (err)
res.send(err);
res.send({message: "User Info created"});
});
});
Expected result :
A example with JSON validator to explain my goal clearly:
But the issue is my code posts data in the following way to the mongo database :
I was wondering if it is possible to post new array object with time attribute instead of having the comma separated values.
Any thoughts and suggestions on this would be appreciated.
Thanks
You are doing it the wrong way.
Try this:
var user = new User();
user.measurements.push({time:req.body.time});
//save the info
user.save(function(err) {
if (err)
res.send(err);
res.send({message: "User Info created"});
});
});
I'm trying to create a Document Schema where I would have a dynamic Object. Example:
var ModuleSchema = new Schema({
name : String,
description : String,
type : String,
age : String,
options : {}
});
Is it possible to do the
options : {}
like that? with any arbitrary attributes inside. I'm getting TypeError: Cannot read property 'find' of undefined when I try to access a route /api/something to get all the documents in the collection. It might be because of the way I've defined the schema. any ideas?
EDIT:
var Module = require('../models/module');var auth =require('../config/auth');module.exports = function(router,Module){
router
.get('/api/modules' , auth.checkAuth, function(req,res){
Module.find(function(err,modules){
if(err){
res.send(err);
}else{
res.json(modules);
}
});
})
.post('/api/modules' , auth.checkAuth,function(req,res){
var module = new Module();
console.log(req.body);
module.name = req.body.name;
module.type = req.body.type;
module.description = req.body.description;
module.age = req.body.filename;
module.options = req.body.options;
module.save(function(err,module){
if(err){
res.send(err);
}else{
res.json({ id : module._id});
}
});
});
I use something like this.
// Importing the Users Mongoose Scheme
var User = require('../app/models/user');
var Feed = require('../app/models/ufeed');
module.exports = function(app) {
// A Route to get all users info
app.get('/user/all', function(req, res) {
// use mongoose to get all users in the database
User.find(function(err, user)
{
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
{
res.send(err);
}
// return all todos in JSON format
res.json(user);
});
});
Within my server.js file I am creating an app like so.
var app = express();
And then passing it to my routes file.
require('./app/routes.js')(app); // load our routes and pass in our app
I hope this helps.
I am new in Node Js and trying to learn it. I am currently follow this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ but its incomplete.
I want, if I click on any user from the list of users, it will take me to new page and show the record in form for update. I don't know how to send data onclick, find the record from the db and show it inside a form to update.
Here is the index file with all the functions:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*Get Hello world page*/
router.get('/helloword', function(req, res){
res.render("Helloworld", {title:'Hello, World!'});
});
/*Get UserList*/
router.get('/userlist', function(req, res){
var db = req.db;
var collection =db.get('usercollection');
collection.find({}, {}, function(e, docs){
res.render('userlist',{
"userlist": docs
});
});
});
/*Get New User Page*/
router.get('/newuser', function(req, res){
res.render('newuser',{title: 'Add New User'})
});
/* POST to Add User Service */
router.post('/adduser', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : userName,
"email" : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
res.redirect("userlist");
}
});
});
module.exports = router;
Thanks in advance please help me for guidance
It looks like you want to use findAndModify (docs)
Using your code you could implement an update route like so.
router.post('/user/:userId', function (req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
collection.findAndModify(
{_id: req.query.userId}, // query
[['_id', 'asc']], // sort order
{
$set: {
"username": userName,
"email": userEmail
}
}, // replacement
{}, // options
function (err, object) {
if (err) {
console.warn(err.message); // returns error if no matching object found
} else {
console.dir(object);
}
});
});
However this does not have any validation to make sure that the user has the correct permissions to update this, make sure you add something like the query
{$and: [{_id: req.query.userId}, {createdBy: req.user}]}
Im running Express on my application with a delete route below:
router.route('/lists/:id')
.delete(function(req, res){
Entry.remove({
_id: req.params.id
}, function(err, list){
if(err)
res.send(err)
list.title = req.body.title;
res.json({message: 'successfully deleted'});
console.log('DELETE on /lists/'+ req.params.id);
});
});
Here is my Mongoose schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ListSchema = new Schema({
title: String
});
module.exports = mongoose.model('List', ListSchema);
When my application hits the delete route, my terminal logs the appropriate statement, but the model is not deleted from the database. When I call fetch on the collection, all of there records are still there.
I am using a very similar approach on a different collection of data on my website, and it works fine, so Im really at a loss for why this is happening.
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assiged is an ObjectId to coincide with MongoDBs default behavior
Try passing the _id as ObjectId:
var ObjectId = require('mongoose').Types.ObjectId;
var query = { _id: new ObjectId(req.params.id) };