So i'm trying to simply update a document in my database, i had no issues with getting data from the database. Here is my code:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/mongo-exercises", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
//Creating Schema
const courseSchema = new mongoose.Schema({
tags: [String],
date: Date,
name: String,
author: String,
isPublished: Boolean,
price: Number,
});
//Creating model which returns a Class
const Course = mongoose.model("courses", courseSchema);
async function updateData(id) {
try {
const course = await Course.findById(id);
course.isPublished = true;
course.author = "another author";
const resulti = await course.save();
console.log(result);
} catch (error) {
console.log(error.message);
}
}
updateData("5a68fdf95db93f6477053ddd");
Error i recieve:
Cannot set property 'isPublished' of null
Any pointers are appreciated thanks in advance:)
I found the solution, the database i was using had deprecated formatting for the id:s.
//In my database
_id: "5a68fdd7bee8ea64649c2777"
//How it should look
_id: ObjectID("5a68fdd7bee8ea64649c2777")
Related
Username doesn't get updated after running this. I also tried UpdateOne and it didn't work as well. The code was supposed to update an array but I tried updating the username to make it easier to track down the problem.
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const userSchema = new schema({
Username:{
type: String,
required: true
},
Password:{
type: String,
required: true
},
Cart: Array
});
const User = mongoose.model('User', userSchema);
module.exports = User;
.
app.post('/putbox', (req, res) => {
var query = { Username: user };
var newvalues = { $push: { Cart: "Boxing" } };
try{
User.find(query).then((d)=>{
var values = d[0].Cart;
values.push("boxing")
User.findByIdAndUpdate(d._id, {Username: "test1"})
});
} catch(err) {
console.log(err);
}
res.redirect('/boxing');
});
I believe the syntax is not correct. The first element of updateOne searches for matches to update. You are just passing d._id which is not the same as the _id key in your db structure. Try this one
User.updateOne({ _id: d._id }, {Username: "test1"})
when i use user.update query it updates none of the user.
it returns null .
i want to push Array in my existing Record
Model:
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt')
var schema = new Schema({
email: { type: String, require: true },
username: { type: String, require: true },
password: { type: String, require: true },
creation_dt: { type: String, require: true },
tasks:[{type:{type:String}}]
},
);
module.exports = mongoose.model('User',schema)
This is the Model i'm using and I want to push some data in tasks[]
Code :
router.post('/newTask', function (req, res, next) {
var dataa = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime
}
var usr = new User(req.user)
usr.update(
{_id:req.user._id},
{$push:{tasks:dataa}}
)
console.log(usr)
try {
doc = usr.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
})
_id:req.user.id returns the exiting id and i want to push data in that used which user is going to post and show user specific data
Output:
Can someone Solve this Problem??
at last I want user specific data I tried a lot with more and more twist but sometimes it update same record for 2 times sometimes it updates nothing I don't know what I can do next.
Thank You
There are two issues.
1, user.save() is async, so you have to await it's return if you want to use doc.
2, you are creating a new User instead of updating a User that already exists.
This code fixes both issues:
router.post('/newTask', async function (req, res, next) {
var data = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime
}
try {
const user = await User.findById(req.user.id);
user.tasks.push(data);
const doc = await user.save();
return res.status(200).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
});
I am having a bit of an issue with Mongoose/MongoDB this afternoon. I have a situation where I need to return all items from a collection, and doing so means that I do not pass in any search params to mongoose.find().
This is the controller that handles the get all request:
exports.get_all_posts = async (req, res, next) => {
const { params } = req;
const { sortby } = params;
//Sortby param takes two arguments for now: most_recent, oldest
try {
const getAllPosts = await BlogPost.find({}, { _id: 0 });
console.log(getAllPosts);
if (!getAllPosts) throw new Error('Could not get blog posts.');
res.json({
posts: date_.sort(getAllPosts, sortby)
});
} catch (error) {
next(error);
}
};
This is particularly where I think the issue is coming from:
const getAllPosts = await BlogPost.find({}, { _id: 0 });
I am passing an empty search parameter and then removing the _id so that it doesn't throw an error telling me that I need to provide the _id.
However I still need to be able to pull in all of the posts. My items from this collection return as normal, just without their _id's.
Here is my model for the blog posts:
const mongoose = require('mongoose');
const BlogPostSchema = new mongoose.Schema({
date: {
type: Date,
required: true
},
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
likes: {
type: Number,
required: false
},
post_body: {
type: String,
required: true
},
description: {
type: String,
required: true
},
tags: [
{
type: String,
required: false
}
],
featuredImage: {
type: String,
required: false
},
draft: {
type: Boolean,
required: true
}
});
module.exports = mongoose.model('BlogPost', BlogPostSchema);
One thing to note is that I have not defined an _id. Mongoose automatically adds in the _id field before saving a schema, so I think it is okay without it, as it has been in the past.
Thanks in advance for reading and any input!
Just as Joe has commented, { _id: 0 } as the second parameter is making your query not return the _id field.
Also as he said, there should be no problem whatsoever with using find({}).
Since other than what has already been stated, I couldn't figure out any mistake in the code snippets you provided, I guess this error could be coming from somewhere else in your project.
exports.get_all_posts = async (req, res, next) => { const { params } = req; const { sortby } = params;
try { const getAllPosts = await BlogPost.find({}); console.log(getAllPosts); if (!getAllPosts) throw new Error('Could not get blog posts.'); res.json({ posts: date_.sort(getAllPosts, sortby) }); } catch (error) { next(error); } };
no need to {_id:0} in the find() method because this method retrieve all the documents in the db collection
What I am trying to do is create a new collection, and push that collection into a specific User.collections array. I have read many stackoverflow posts and they all say to use either User.update() or User.findOneAndUpdate(). I am have no luck with either. I can create a Collection and that is saved to mongo so I know I am indeed accessing the db. Here is my code, if any of you can help I would appreciate it.
User Schema
const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
googleID: String,
givenName: String,
familyName: String,
collections: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "collection"
}
]
});
mongoose.model('users', userSchema);
Collection Schema:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const collectionSchema = new Schema({
type: String,
name: String,
gamesCollected: [
{
id: Number
}
]
});
mongoose.model('collection', collectionSchema);
And my route:
router.get('/get_collection', (req, res) => {
const collection = new Collection({
type: 'SNES',
name: 'First SNES Collection',
gamesCollected: [{ id: 5353 }]
}).save();
User.update({googleID: req.user.googleID}, {$push: {collections: collection}});
});
Save is not a synchronous operation but asynchronous so you need to use the promise it returns and handle it and once it is complete then update the user model. Something among these lines:
router.get('/get_collection', async (req, res) => {
let collection = new Collection({
type: 'SNES',
name: 'First SNES Collection',
gamesCollected: [{ id: 5353 }]
})
await collection.save().exec();
await User.update(
{googleID: req.user.googleID},
{$push: {collections: collection._id}}
).exec();
});
I have a problem with mongoose
mongoose queries don't return mongoose document instances
Here is my Schema:
const mongoose = require('mongoose');
var AlbumSchema = new mongoose.Schema({
name: String,
cover: String,
releaseDate: Date,
}, {
timestamps: true,
});
AlbumSchema.index({name:'text'});
export const Album = mongoose.model('Album', AlbumSchema);
and this is my query:
import {Album} from './Album'
Album.create({
name:"Eddie",
}).then((album)=>{
console.log(album);
})
result:
{ _id: 5a575b82d921be1fc0aa8b44,
name: 'Hogtw',
createdAt: 2018-01-11T12:41:38.711Z,
updatedAt: 2018-01-11T12:41:38.711Z,
__v: 0 }
If you want to a mongoose object when creating data, the alternate way is to use .save() method it will return mongoose object in a callback.
let album = new Album({ name: 'Eddie' });
album.save(function (err, savedAlbum) {
if (err) {
// show err //
}
else {
// show response
}
})