Create a new document using MEAN mongoose - node.js

i'm new to mongoose and mongodb, i'm trying to create a new document inside my collection.
I'm able to update existing one or get all the document from the collection.
I need to create a new document based on the collection (I have a single collection now). - createMoment function.
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://url and pass');
var usersSchema = require('./users_schema').usersSchema;
mongoose.model('usersM', usersSchema);
var usersAction;
mongoose.connection.once('open',function(){
var Users = this.model('usersM');
var query = Users.find();
query.where('userId');
query.exec(function(err, docs){
usersAction = docs;
console.log("docs: " + usersAction);
return usersAction;
});
});
exports.getData = function(){
return usersAction;
};
exports.createMoment = function(_fn, _ln, _conc,_lan,_lat,cb){
var Users = mongoose.model('usersM');
console.log("createMoment Called");
Users.insertOne({
'leadRank':1,
'adminApproval':true,
'userFname':_fn,
'userLname':_ln,
"conclusion":_conc,
'tentCoor':{'latitude' : _lat, 'longitude' : _lan}
}, null, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the users collection.");
cb(result);
});
};
My schema:
I'm not passing some of the fields yet
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var usersSchema = new schema({
campName: {type:String, required:true},
centerCoor: [{
latitude:{type:Number},
longitude:{type:Number}
}],
zoom: {type:String},
users: [{
leadRank: {type:Number},
adminApproval: Boolean,
userFname: {type:String, required:true},
userLname: {type:String, required:true},
conclusion: {type:String},
tentCoor: [{
latitude:{type:Number},
longitude:{type:Number}
}]
}]
}, {collection: 'camps'});
exports.usersSchema = usersSchema;

Related

How to populate without using ref in mongoose

I was doing NodeJS project which is using 2 database
Assosiates
outlets
Now I want to execute one query which uses populate and in my database I didn't use any "ref" relation
Is there any way to execute query using populate method without changing my database schema?
This is my associate schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;
var AssociateSchema = new Schema({
category_id:{type: ObjectId, max: 100},
associate_name: {type:String,max: 100},
associate_address: {type:String,max: 500},
associate_no: {type:Number},
associate_emaiid: {type:String,max: 100},
associate_status: {type:Boolean},
});
Associate= mongoose.model('Associate', AssociateSchema);
module.exports = mongoose.model('Associate', AssociateSchema);
This is my outlet schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;
var OutletSchema = new Schema({
associate_id:{type:ObjectId, max: 100},
outlet_name: {type:String,max: 100},
outlet_address: {type:String,max: 500},
outlet_no: {type:Number},
outlet_status: {type:Boolean},
city_id:{type:ObjectId, max: 100},
});
module.exports = mongoose.model('Outlet', OutletSchema);
This is the query I am using:
router.get('/getma', function (req, res) {
Associate.findOne({ _id: '' })
.populate('outlets')
.exec(function (err,dea) {
if (err) return handleError(err);
console.log(dea)
res.json(dea)
})
});

"Item" schema is not found even i required that model.(mongoose,Node.js)

I am trying to run hook of 'remove' in label schema."Item.find is not a function" this is the error which I got.
But 'Item' schema is not found.This "require" works fine on other models.Here it is not working.
That error might be occurs in var Item = require('./Item');
This is "Label" schema.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Item = require('./Item');
var List = require('./List');
// created schema for Item
var labelSchema = new Schema({
label_title: {type: String},
color_id:{type: String, required: true},
created_at: Date,
updated_at: Date,
marked : { Boolean ,default:false },
_board: {type: Schema.Types.ObjectId, ref:'Board'}
});
//-----------------Hook--
labelSchema.post('remove',function(doc,next){
Label.remove({_id:this._id}).then(function(data){
console.log("successfuly removed label");
}).catch(function(error){console.log(error);
})
//-----remove label from all items
// console.log("ITEM", Item);
Item.find({},function(error,items){
items.forEach(function(item){
Item.findByIdAndUpdate(item._id,
{ "$pullAll": { "label" : [{ "label_id" : this._id }]} },function(error,result){
if(result)console.log("successfully removed");
else console.log("not removed");
})
})
})
});
var Label = mongoose.model('Label', labelSchema);
module.exports = Label;
What should I do?

Nodejs include Models

Im having problems to make my server.js use my models.
I do have other models with same structure, like for example:
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
but they works fine.. somehow.
But if If i try to use:
var Crime = mongoose.model('Crime');
i get:
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Crime".
if i switch to:
var Crime = require('./models/Crime');
or
var Crime = require('./models/Crime.js');
i get the response:
Cannot find module './models/Crime'
Crime model code:
var mongoose = require('mongoose');
var CrimeSchema = new mongoose.Schema({
username: {type: String, lowercase: true, unique: true},
time: String,
salt: String
});
CrimeSchema.methods.performCrime = function(pass) {
/*var deferred = $q.defer();
deferred.notify('loading....');
deferred.reject('Greeting is not allowed.');
return deferred.promise;
*/
return 22;
};
mongoose.model('Crime', CrimeSchema);
EDIT
example of working model:
var Post = mongoose.model('Post');
and post.js model
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
PostSchema.methods.upvote = function(cb) {
this.upvotes += 1;
this.save(cb);
};
PostSchema.methods.downvote = function (cb) {
this.upvotes -= 1;
this.save(cb);
};
mongoose.model('Post', PostSchema);
You forgot to export the module at the end.
var Crime = mongoose.model('Crime', CrimeSchema);
module.exports = Crime;

Mongoose populate across 2 databases

I have a node app that uses 2 databases. One is the the Names and the other for the rest of all the data.
I have this connection setup:
// DATABASE CONNECTION
var APP_DB_URI = config.APP_DB; // mongodb://localhost:27017/app_db
var app_DB = mongoose.createConnection(APP_DB_URI);
var name_DB = app_DB.useDb(config.NAME_DB); // 'name_db'
This connection is working properly.
There's also no problem upon saving data to both app_db and names_db working perfect.
But the problem is this: when I try to query let say the Account model and then populate the referenced Name model, the populate process returns null.
Account schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var field = {
email: {type: String, unique: true},
password: {type: String, select: false},
name: {type: Schema.Types.ObjectId, ref: 'Name'},
}
var options = {
id: false,
versionKey: false
}
var schema = new Schema(field, options);
module.exports = mongoose.model('Account', schema);
Name schema:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var field = {
firstName: {type: String, required: true},
middleName: {type: String, required: true},
lastName: {type: String, required: true},
suffix: {type: String, required: false,},
}
var options = {
id: false,
versionKey: false
}
var schema = new Schema(field, options);
module.exports = mongoose.model('Name', schema);
The query and population:
var app_db = *app_db instance passed to this controller*
var Account = app_db.model('Account');
Account.findOne({email:req.body.email})
.populate('name')
.exec(function (err, user) {
if(user){
// user.name returns null
}
})
Is there a special way to populate data from db1 the data from db2? Thanks.
Populate Mongo documents across databases feature added since mongoose v3.9.0. Per this across db populate test, you should different db name when model is called. Some sample codes as below. More details please refer to the test codes in the link.
var app_DB = mongoose.createConnection(APP_DB_URI);
var name_DB = app_DB.useDb(config.NAME_DB); // 'name_db'
// ...
module.exports = app_DB.model('Account', schema);
// ...
module.exports = name_DB.model('Name', schema);
Populate
.populate('name', '', Name)

Mongoose populate not returning results

I am trying to use populate to return results that are ref to the Stamp model, under the users array of stamps but for some reason it does not return any results when I see in the database a list of stamp ids in the stamps array...
Here is my code:
var selectQuery = "_id name";
var populateQuery = [{path:'stamps', select: selectQuery, model: 'Stamp', }];
User.findOne({_id: userId}).populate(populateQuery).sort({date: -1}).skip(count).limit(100).exec(function(err, results) {
if(err) {
Here is the User Schema
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId,
var Stamp = require('../models/stamp.js');
var User = new Schema({
name: { type: String},
stamps: [{ type: ObjectId, ref: 'Stamp' }],
The "query" form of populate doesn't take an array as argument, but an object:
// `model` can be left out as Mongoose will look that up in the schema
var populateQuery = { path : 'stamps', select : selectQuery };

Resources