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)
})
});
Related
I have a mongoose collection that sorts by first added, and I want it to sort by last edited
The model
var mongoose = require("mongoose");
var user = require("./user");
var questionSchema = new mongoose.Schema({
text: String,
asked: String,
answer: String
})
module.exports = mongoose.model("question", questionSchema);
The put request code:
router.put("/:user/:id", checkOwner, function(req, res){
question.findByIdAndUpdate(req.params.id, req.body.question, function(err,
updatedQuestion){
if(err) {
console.log(err);
} else {
res.redirect("/");
}
});
});
I want that updatedQuestion to be on the top my collection
Here is one simple approach:
First you have to add timestamps in your mongoose model, in order to have access on createdAt and updatedAt proerties.
You can see more about timestamps here
var mongoose = require("mongoose");
var user = require("./user");
var questionSchema = new mongoose.Schema({
text: String,
asked: String,
answer: String
},
{ timestamps: true}
)
module.exports = mongoose.model("question", questionSchema);
Then you can query your collections, applying sorting by updatedAt
question.find({}, {}, {sort: { 'updatedAt' : -1 }})
Thus the most recent updated document will be shown first.
I have two collection like this:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var GradeSchema = new Schema({
gID: { type: Number, ref: 'User'},
grade: Number,
created_at: Date,
updated_at: Date,
type: Number
});
var Grade = mongoose.model('Grade', GradeSchema);
module.exports=Grade;
and:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: String,
lastName:String,
uID: { type: Number,ref:'Grade' },
phone: String
});
var User = mongoose.model('User', UserSchema);
module.exports=User;
how can i first aggregate and then populate to have both collection information??
i used this command using $lookup in mongodb and it return my suggested documents:
db.grades.aggregate([{$lookup
{from:"users",localField:"gID",foreignField:"uID",as: "result"}},{$match:
{"type":0}},{"$sort":{"grade":-1}}])
but when i used this in mongoose the "result" is [] and connection to user collection is failed:
Grade.aggregate([{"$lookup":
{"from":"User","localField":"gID","foreignField":"uID","as": "result"}},
{"$match":{"type":3}},{"$sort":{"grade":-1}}]).exec(function(err, data)
{console.log(data);});
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)
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;
I am trying to create a hierarchy of categories in MongoDB for use with Node.js via Mongoose. I am using the Array of Ancestors approach (http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-ancestors-array/) and have already saved the hierarchy in the database. Directly from Mongo an element looks like this:
{
"_id" : "Football",
"ancestors" : [
"Categories",
"Sports and fitness"
],
"parent" : "Sports and fitness"
}
I have created a model and controller for the categories, and are as of now having problems querying the database.
This is the code in model/Category.js:
var mongoose = require('mongoose');
var Category = mongoose.Schema({
_id: String
});
var categorySchema = mongoose.Schema({
ancestors: [Category],
parent: [Category]
});
// Initiate database connection
var db = mongoose.createConnection('mongodb://localhost/Categories');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("openDB categories");
});
module.exports.category = db.model('Category', categorySchema);
This is the controller:
var categoryModel = require('../models/Category');
var Category = categoryModel.category;
exports.getAncestors = function(req, res) {
if (req.params.id == undefined){res.send("no id specified!"); return;}
Category.findOne({_id: 'Football'}, 'ancestors', function(err, ancestors){
if(err) console.log(err);
res.send(ancestors);
});
}
When running this code I get the following error message:
{ message: 'Cast to ObjectId failed for value "Football" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'Football',
path: '_id' }
I believe the problem may be in the mongoose schema, but all help is greatly appreciated.
Many thanks!
Mongoose tries to set an ObjectId by default. You can suppress this with the following:
var categorySchema = mongoose.Schema({
_id: String,
ancestors: [{type: String }],
parent: {type: String}
},{ _id: false });
var Category = mongoose.model( "Category", categorySchema );
And noting that there is only one schema for you layout.