I am trying to find a document from mongo, but the findOne() brings the document with an undefined _id field.
why?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/school');
var Schema = mongoose.Schema;
var scoreSchema = new Schema({
type: String,
score: Number
});
var studentSchema = new Schema({
name: String,
scores: [scoreSchema]
});
var mod = mongoose.model('Student', studentSchema);
mod.findOne(function(err, stud) {
console.log('id:' + stud._id);
});
You need to pass something to find in your query. For example:
mod.findOne({name: 'John'}, function(err, stud) {
console.log('id:' + stud._id);
});
See here on how to make queries in Mongoose.
You're not querying anything, notice the {} before the callback.
mod.findOne({}, function(err, stud) {
console.log('id:' + stud._id);
});
You might want to have a look at the Mongoose documentation.
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 been given some code to modify. It is a Node.js app using Mongoose to interact with a MongoDb instance. In Mongoose several schemas were already set up and I've added a few. Among those are these two schemas which break apart a previously existing schema (which was working fine with small data):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MapConvertedProjectSchema = new Schema(
{
project_id : {
type: String,
default: ""
},
dataset_id : {
type: String,
default: ""
},
properties:{
type: {},
default: {}
}
});
MapConvertedProjectSchema.pre('save', function(next) {
next();
});
mongoose.model('MapConvertedProject', MapConvertedProjectSchema);
and
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MapConvertedLayerSchema = new Schema(
{
parent_id:
{
type: mongoose.Schema.Types.ObjectId
},
class:
{
type: String,
default: 'MapLayer',
trim: true
},
properties:
{
type: {},
default: {}
}
});
//Hook a pre save method to clean date
MapConvertedLayerSchema.pre('save', function(next) {
next();
});
mongoose.model('MapConvertedLayer', MapConvertedLayerSchema);
I use the MapConvertedLayer schema like so:
var mongoose = require('mongoose');
var LayerConverted = mongoose.model('MapConvertedLayer');
var newLayer = new LayerConverted();
//newLayer._id is automatically populated with a value
//... add other properties
newLayer.save(function(err)
{
if(err)
{
//...
}
});
This works without any issues that I can discern. However if I try similar code with MapConvertedProject I get an error:
var mongoose = require('mongoose');
var ProjectConverted = mongoose.model('MapConvertedProject');
var map_converted = new ProjectConverted();
//map_converted._id is undefined
//I tried adding the comment below to create an _id manually, but it didn't make a difference when I tried to save
//map_converted._id = mongoose.Types.ObjectId();
console.log("Project Converted ID: " + map_converted._id);
//... fill out the other properties on the schema
map_converted.save(function(err)
{
if(err)
{
//...
}
});
The save generates this error:
ValidationException: One or more parameter values were invalid: Missing the key _id in the item
Does anyone know what is causing this?
I figured this out. There was another place in the code that had a dynamoose model with the same name that was messing things up. I was able to remove all references to dynamoose since it doesn't appear to be used anymore and that cleared up this issue.
I need to read a collection identified connected to a mongoose model. Is the correct approach to read the property model.schema.options.collection directly or is there any more suitable approach?
As far as i have understood, you want to use the property of your mongoose schema. i will provide you with a small example to how you can use it effectively.
Your model file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//Schema for User
var UserSchema = new Schema({
name: {
type: String,
},
email: {
type: String
},
password: {
type: String,
},
});
module.exports = mongoose.model('User', UserSchema);
In your function where you want to include this model
var User = require('/path/models/user');
var UserController = {
create: function(req, res){
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
//rest of the functionality on these bod params.
}
}
I hope this small example will be able to help.
I am using the following Mongoose Schema :
var userSchema = new mongoose.Schema({
...
sentFriendsRequests: [{
type : ObjectId,
}]
)};
I am adding some ObjectIds to the sentFriendsRequests
User.update({ _id: userId },
{ $push: { sentFriendsRequests: targetId }},
{safe: true, upsert: true}, function(err, result) {
if (err || !result) {
done(err);
}
done(null);
});
This seems to be working properly, because as I am using Mongolab to host my Database, when displaying documents on screen I can see that the ObjectIds are added to the array with success :
"receivedFriendsRequests": [
"5720c659571a718705d58fc3"
]
The weird thing is that when querying this array, Mongoose always return an empty one...
User.find({ _id: userId}, function(err, res) {
console.log(res[0].sentFriendsRequests);
});
// prints []
Have confusion of mongodb with mongoose.
Mongoose need define Schema but mongodb is nope.
To define new ObjectId in mongodb:
var ObjectId = require('mongodb').ObjectID
var objectId = new ObjectID();
in Mongoose:
var mongoose = require('mongoose');
var objectId = new mongoose.Types.ObjectId;
I finally found that using var ObjectId = require('mongodb').ObjectID; makes Mongoose to return empty array, whereas using mongoose.Schema.Types.ObjectId works properly. I don't know how to explain this.
I am using a MEAN stack to build this application.
Here is my subject.js schema:
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var topics = require('./topic');
var subjectSchema = new schema({
_category : {
type: String,
default: ""
},
topics: [topics.schema]
});
module.exports = mongoose.model('Subject', subjectSchema);
and my topics.js schema:
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var otherstuff = require('./otherstuff');
var otherstuff2 = require('./otherstuff2');
var topicSchema = new schema ({
title: String,
otherstuff: [mongoose.model('otherstuff').schema],
otherstuff2: [mongoose.model('otherstuff2').schema]
});
module.exports = mongoose.model('Topic', topicSchema);
What I am having difficulty with is how to access my topicSchema to populate it with forms from my front end.
I can save information to the subjectSchema, but not the sub documents.
I have tried using this as outlined in another article:
var Subject = mongoose.model('Subject', subjectSchema);
Subject.find({}).populate('subjects[0].topics[0].title').exec(function(err, subjects) {
console.log(subjects[0].topics[0].title);
});
But I continue to get TypeError: Cannot read property 'title' of undefined. How do I access the title property?
populate in mongoose is used to populate referenced documents, that are marked with ref attribute (see more info in the docs). Sub-documents on the other hand are available when do a simple query because they are actually an array of custom objects, so if you remove the populate method your query will work as expected:
Subject.find({}).exec(function(err, subjects) {
console.log(subjects[0].topics[0].title);
});