NodeJS - MongooseJS schema error that i cant figure out - node.js

Maybe a second set of eyes can see what is wrong with my schema
var UserSchema = new Schema({
name:
{
first : {type: String}
, last : {type : String}
}
, password: {type: String}
, username: {type: String}
, role: RoleSchema
, created_at : {type : Date, default : Date.now}
, modified_at : {type : Date, default : Date.now}
})
var RoleSchema = {
type: [String]
, study_type: [String]
}
mongoose.model('User', UserSchema)
The Error:
TypeError: Invalid value for schema path `role`

The embedded Schema (Roles) needs to be above the UserSchema

In addition to the Roles schema having to be imported before the UserSchema.
In the newer versions of mongoose the following sort of syntax was also needed for to get beyond the 'TypeError: Invalid value for schema Array path:
var SomeSchema = new mongoose.Schema();
SomeSchema.add({
key1: {
type: String,
required: true
},
key2: {
type: String,
required: true
},
key3: {
type: String,
required: true
}
});
SomeSchema.get(function(val){
// Remove the _id from the Violations
delete val._id;
return val;
});
And the parent:
var ParentSchema = new mongoose.Schema({
parentKey: String,
someArray: [SomeSchema]
})
module.exports = mongoose.model('Parent', ParentSchema)
This happened when switching from mongoose 3.x to 4.x

Related

Sort by reverse order mongoose

Hi, I am trying to return my query in backwards order from which it was created.
The docs are a little unclear on how to use the sort method:
http://mongoosejs.com/docs/api.html#types_array_MongooseArray.sort
Here is my schema:
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.Types.ObjectId;
let PostSchema = new Schema({
title : String,
description: String,
image : String,
tags : [String],
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
date: {
type: Date,
default: new Date()
}
})
module.exports = mongoose.model('Post',PostSchema);
I have run,
db.posts.find().sort({date:-1}).pretty()
For example, if my model was a 'Post' model and my first post was 'hello world' and my second post was 'this is a post'. I would like to see:
['this is a post', 'hello world']
However, what I am actually seeing is ['hello world','this is a post']
Figured out the answer
in posts schema add:
date: {
type: Date,
default: Date.now
}
then db.posts.find().sort({date:-1}).pretty() will yield the posts sorted from most recent to least recent
You have to add a creation timestamp in your schema and sort by its key.
let PostSchema = new Schema({
title : String,
description: String,
date : Date, // Here is your date
image : String,
tags : [String],
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
})
and when you insert a document, use:
date: new Date()

How to populate _id field with string filed in mongodb node.js?

I have two collections user and comments.In user there is fields :
const user = mongoose.Schema({
_id :("In the form of ObjectID"),
//ObjectId("5a19086e0664e832842f2c24")
user_name :{type: String},
password : {type: String}
});
and comments collection:
const comments = mongoose.Schema({
user_id :{type: String},
//"5a19086e0664e832842f2c24" this is user's _id
comment : {type: String}
});
Now I want to know that how to populate this 2 collection with the user's _id which is in string type in comment collection.
Thankyou in advance
I think you already can use String to populate an ObjectId like this :
const user = mongoose.Schema({
user_name : {type: String},
password : {type: String}
}); // users._id will natively be an ObjectId
const comments = mongoose.Schema({
user_id : {type: String, ref:'users'}, // user_id has to be referenced with your "users" model
comment : {type: String}
});
Comment.find({}).populate('user_id').exec();
Hope it helps.
At first you need to update your schema as it requires the reference of the collection you want to populate:
const user = mongoose.Schema({
user_name: { type: String },
password: { type: String }
});
const comments = mongoose.Schema({
user_id: { type: Schema.Types.ObjectId, ref: 'User' },
comment: { type: String }
});
Note: I removed the _id field as it will be added automatically. Also take note that _id is an ObjectId not just a string (even though you can consider it as a string).
Then you can use the populate() method:
Comments.find({}).populate('user_id').exec()

Mongoose Populate Method is not populating value

I have two mongoose schema as following
var ServiceSubType = new Schema({
displaySubTypeName : String,
subTypeDescription : String,
status : { type: String, default: Constants.ACTIVE },
lastUpdatedOn : Date,
createdOn : { type: Date, default: Date.now }
} , { collection: 'SERVICE_SUB_TYPES' });
and
var ServiceType = new Schema({
displayName : String,
description : String,
status : { type: String, default: Constants.ACTIVE },
lastUpdatedOn : Date,
serviceSubTypeId : {type: Schema.Types.ObjectId, ref: 'ServiceSubType', index: true},
createdBy : { type: Schema.Types.ObjectId, ref: 'SystemUser', index: true },
createdOn : { type: Date, default: Date.now }
} , { collection: 'SERVICE_TYPES' });
I have populated Type Object as below
module.exports.addNewServiceType = function(serviceType_obj, callback) {
serviceType_obj.save(serviceType_obj,callback);
}
Now I am trying to populate ServiceSubType document and then at the same time trying to populate "serviceSubTypeId" of ServiceType object referenced to ServiceSubType created.
Here is my piece of code for the same purpose.
module.exports.addServiceSubType = function(serviceTypeObjId, serviceSubType_obj, callback) {
serviceSubType_obj.save(serviceSubType_obj, function (error, serviceSubType) {
});
serviceSchema.ServiceType.findById(serviceTypeObjId, function (err, serviceType) {
var opts = { path: 'serviceSubTypeId'};
serviceSchema.ServiceType.populate(serviceType, opts, function (err, user) {
console.log(serviceType);
});
}).exec(callback);
}
But it is not workign and not populating any value in Existing SubType object.
I admit my approach could be very wrong as I am very new in this technology. Appreciate any kind of help to run this piece of code as expected.
Thanks
Ajoy
I think your ref should be the same setting as the collection on the object
serviceSubTypeId : {
type: Schema.Types.ObjectId,
ref: 'SERVICE_SUB_TYPES', <==== your collection type goes here
index: true
},
Mongoose doesn't know anything about your JavaScript object types. Instead, it tracks things based on the collection name that you provide (or that it generates).
update based on comments below
I have some example code that I wrote a while back, and it looks like I'm letting Mongoose generate the collection name for me. However, I am supplying a name to the mogoose.model() call, when registering my type for a collection.
For example, I have a Post type and a User type. The Post contains an author which is a reference to the User.
It looks like this:
// post
// ----
var PostSchema = new mongoose.Schema({
date: {type: Date, required: true, default: Date.now},
title: {type: String, required: true},
content: {type: String, required: true},
author: {
type: SchemaTypes.ObjectId,
ref: "user"
},
comments: [CommentSchema]
});
var Post = mongoose.model("blog", PostSchema);
// user
// ----
var UserSchema = mongoose.Schema({
firstName: {type: String},
lastName: {type: String},
username: {type: String, required: true, index: {unique: true}},
email: {type: String, required: true},
password: {type: String, required: true},
url: {
type: mongoose.Schema.Types.ObjectId,
ref: "url"
}
});
User = mongoose.model("user", UserSchema);
In this example code, I'm setting the ref to "user" because I am registering my model as "user" down below, in the mongoose.model method call.
Are you registering your models using mongoose.model and supplying a name? if so, use that name.

Node.js - Create Relationships with Mongoose from different file

I have two Schemas Products and Users in different files. Products are belong to User and User have many Product
The Problem is, I have try to use Populate but somehow it return not what I expected.
here is my Schema for Product on models products.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var users = require('../models/users');
var Product = mongoose.Schema({
user_id : {type: String, required: true },
category_id : {type: String, default: null},
title : {type: String, required: true },
content : {type: String, default : "" },
pictureUrls : Array,
counter : {type : Number, default : 0},,
lowercaseTitle : {type: String, default : null },
_user : { type: Schema.Types.ObjectId, ref: users.User }
});
Product.set('toObject', {
getters: true,
virtuals: true
});
module.exports = mongoose.model('Product', Product)
and this is my Schema for User on models users.js
var mongoose = require('mongoose');
var User = mongoose.Schema({
firstName : {type: String, default: "" },
lastName : {type: String, default: "" },
username : {type: String, required: true },
email : {type: String, required: true },
password : {type: String, default: "" },
bio : {type: String, default: "" },
website : {type: String, default: "" },
phone : {type: String, default: "" },
gender : {type: String, default: "" },
birthDate : {type: Date, default: null },
avatarUrl : {type: String, default: "" },
verified : {type : Boolean, default : false}
});
User.set('toObject', {
getters: true,
virtuals: true
});
module.exports = mongoose.model('User', User);
currently I am using method find by calling each Models
User.findOne({"sessionToken" : bearerHeader}, function (err, user){
Product.find({"user_id" : user._id}, function (err, products){
console.log(products);
});
});
but it takes time and became problem if there related to another models.
I'm calling populte with this
Product.findOne({}).populate('_user').exec(function(err, p){
console.log(p);
});
but attribute _user was not set and undefined
any help?
Thanks

Mongoose Sorting

I have a problem with displaying data with sorting. Here is my query,
Activity.find({"user_id": sesUser._id}, {}, {offset: 0, limit : 5, sort:{createdAt:1}}, function (e,a){
...
});
I have data about 252 length, and my latest data is 9 June 2015. If i use this query i only get data from 5 June 2015/ last week data and not get the latest data, but if i not using sorting, the latest data is appear.
I have used this query below but turns out the result is same.
Activity.find({"user_id" : sesUser._id}).sort("createdAt").exec(function(err,a){
...
});
Any help? I'm using Mongoose v3
-- edited --
This is my Activity Schema / Model
var mongoose = require('mongoose');
var Activity = mongoose.Schema({
sender_id : {type: String, required: true },
user_id : {type: String, required: true },
product_id : {type: String, default : "" },
type : {type: String, required: true },
createdAt : {type: String, default : new Date()}
});
module.exports = mongoose.model('Activity', Activity);
`createdAt : {type: Date, default : new Date()}`
Type Date not string man
It will automatically create the createdAt and updatedAt
var options={
timestamps: true
}
var Activity = mongoose.Schema({
sender_id : {type: String, required: true },
user_id : {type: String, required: true },
product_id : {type: String, default : "" },
type : {type: String, required: true }
},options);

Resources