So I am trying to retrieve a course using its id. I've tried using:
Course.findOne({ _id: __id })
Course.findById(id)
I not sure why it's not working, do I have to define _id type in the schema?
Result:
null
Here is my schema + function
const courseSchema = new mongoose.Schema({
name: { type: String, required: true, minlength: 3, max: 255 },
category: {
type: String,
required: true,
enum: ["web", "mobile", "network"]
},
tag: [String],
data: Date,
author: String,
isPublished: Boolean,
price: {
type: Number,
required: function() {
return this.isPublished;
},
min: 10,
max: 200
},
__v: Number
});
const Course = mongoose.model("Course", courseSchema);
async function updateCourse(id) {
// var __id = mongoose.Types.ObjectId(id); // tried converting string id (?)
console.log(id);
// // method 1
const course = await Course.findOne({ _id: __id });
console.log("resulting...", course);
if (!course) return;
course.isPublished = true;
course.author = "Another author";
const result = await course.save();
console.log("saved....", result);
}
updateCourse("5c726f6feb352743f8226239");
MongoDB:
You should not use __id in your Course.findOne call - use _id: _id:
Course.findOne({_id: _id});
Try to replace __id with id.
Course.findOne({_id: id});
Related
in my resolvers I have a method to find user likes with
async function userBookmarks(args, context) {
const user = checkAuth(context);
const posts = await Post.find({likes: {userId: user.id}})
return posts; }
But GraphQL returns an empty array.
For reference, the Post model is
likes: [
{
userId: String,
createdAt: String
}],
I came across a similar problem and fixed it by defining the MongoDB Collection name in the bottom of my MongoDB Schema.
const UserSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
location: {
type: String,
required: false
}
}, { collection : 'Users' });
EDIT:
Use $elemMatch to query several fields.
const posts = await User.find({likes: {$elemMatch: {userId: user.id}}})
MongoDB documents contain an array of objects and what is the best way to query those documents if I want to find and remove an object from an array with some specific value;
Here is an example of the document schema
const mongoose = require("mongoose");
const LibrarySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
books: [
{
type: new mongoose.Schema({
bookName: {
type: String,
required: true,
},
chapterReading: {
type: Number,
default: 1,
required: true,
},
}),
},
],
});
const Library = mongoose.model("Library", LibrarySchema);
exports.Library = Library;
If I want to find and remove a book with some bookName
Use $pull
Example :
Library.update({}, { $pull: { books: { bookName: "Yourbookname" } } })
I'm trying to update a document in a mongo database with information from a form, with all the form going into a field which is an array. At the moment I can't get it to update a document, only create a new one, but more pressingly I can't get the information from the form into the array.
Here is my schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const WorkoutSchema = new Schema({
day: {
type: Date,
default: Date.now
},
exercises: [
{
type: String,
trim: true,
required: "Exercise type is required"
},
{
name: String,
trim: true,
required: "Exercise name is required"
},
{
duration: Number
},
{
weight: Number
},
{
reps: Number
},
{
sets: Number
},
{
duration: Number
},
{
distance: Number
}
]
});
const Workout = mongoose.model("Workout", WorkoutSchema);
module.exports = Workout;
And here is my API route. I've included the results of console.logs below it so you can see the information that is getting passed.
app.put("/api/workouts/:id", (req, res) => {
console.log("api body: " + JSON.stringify(req.body));
console.log("body is " + typeof req.body);
var body = JSON.stringify(req.body);
// body = body.split("{")[1];
// body = body.split("}")[0];
// body = "["+body+"]";
console.log(body);
Workout.create({exercises: `${body}`})
.then(Workout => {
res.json(Workout);
})
.catch(err => {
res.json(err);
});
});
api body: {"type":"resistance","name":"Test Press","weight":100,"sets":5,"reps":6,"duration":10}
body is object
{"type":"resistance","name":"Test Press","weight":100,"sets":5,"reps":6,"duration":10}
In the database I get exercises as an array with one element - the above object - instead of a series of key/value pairs. I've tried a lot of things, but this is as close as I get to what I'm trying to do.
Can anyone see where I've gone wrong?
This turned out to be a basic syntax error which came about because one of my keys was "type". The issue is in the syntax of the exercises array, the model should look like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const WorkoutSchema = new Schema({
day: {
type: Date,
default: Date.now
},
exercises: [{
type: {
type: String,
trim: true,
required: "Exercise type is required"
},
name: {
type: String,
trim: true,
required: "Exercise name is required"
},
duration: {
type: Number,
required: "Duration is required"
},
weight: {
type: Number
},
reps: {
type: Number
},
sets: {
type: Number
},
distance: {
type: Number
}
}]
});
const Workout = mongoose.model("Workout", WorkoutSchema);
module.exports = Workout;
I need to validate the array of objects in my schema
Schema:
user: [{
name: String,
Age: String,
Contact: Number
}]
How to validate name, age and contact.
I assume your user array is inside another schema.
Let's say we have a Course model with users like this:
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
users: [
{
name: { type: String, required: [true, "Name is required"] },
age: { type: Number, required: [true, "Age is required"] },
contact: { type: Number, required: [true, "Contact is required"] }
}
]
});
const Course = mongoose.model("Post", courseSchema);
module.exports = Course;
To validate this in a post route you can use mongoose model validateSync method:
const Course = require("../models/course");
router.post("/course", async (req, res) => {
const { name, users } = req.body;
const course = new Course({ name, users });
const validationErrors = course.validateSync();
if (validationErrors) {
res.status(400).send(validationErrors.message);
} else {
const result = await course.save();
res.send(result);
}
});
When we send a requset body without required fields like age and contact:
(you can also transform validationErrors.errors for more useful error messages.)
{
"name": "course 1",
"users": [{"name": "name 1"}, {"name": "name 2", "age": 22, "contact": 2222}]
}
The result will be like this:
Post validation failed: users.0.contact: Contact is required, users.0.age: Age is required
It will be similar to the usual validation but inside an array, you need to make a validator function as so:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//the custom validation that will get applied to the features attribute.
var notEmpty = function(features){
if(features.length === 0){return false}
else {return true};
}
var CarSchema = new Schema({
name: {
type: String,
required: true,
},
features: [{
type: Schema.ObjectId,
ref: Feature
required: true; //this will prevent a Car model from being saved without a features array.
validate: [notEmpty, 'Please add at least one feature in the features array'] //this adds custom validation through the function check of notEmpty.
}]
});
var FeatureSchema = new Schema({
name: {
type: String,
required: true //this will prevent a Feature model from being saved without a name attribute.
}
});
mongoose.model('Car', CarSchema);
mongoose.model('Feature', FeatureSchema);
By using type key/property:
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'Why no bacon?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea'],
required: function() {
return this.bacon > 3;
}
}
});
I am writing code with node.js. Quite new to this and the problem is that mongoose returns an empty array. There must be a mistake somewhere in this code, but I cannot find it. Any ideas?
Dresses schema
var dressesSchema = mongoose.Schema({
title:{
type: String,
required: true
},
description:{
type: String,
required: true
}
});
var Dress = module.exports = mongoose.model('Dress', dressesSchema);
Get dresses from database
module.exports.getDresses = function(callback, limit){
Dress.find(callback).limit(limit);
};
Dress = require('./models/dress');
app.get('/api/dresses', function(req, res){
Dress.getDresses(function(err, dresses){
if(err){
throw err;
}
res.json(dresses);
});
});
example how to use find via mongoose :
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});
// executes immediately, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// name LIKE john and only selecting the "name" and "friends" fields, executing immediately
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })
// passing options and executing immediately
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});
taken from link
try this:
Dresses schema :
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Dress= new Schema({
title:{
type: String,
required: true
},
description:{
type: String,
required: true
},
price:{
type: String
},
stock:{
type: String
},
location:{
country:{
type: String
},
city:{
type: String
},
street:{
type: String
},
lon:{
type: String
},
lat:{
type: String
}
}
});
module.exports = mongoose.model("dress", Dress);
Get dresses from database:
const {Dress} = require('./models/dress');
Dress.find().then(result => {
console.log(result);
});