document must have an _id before saving mongoose error - node.js

I am trying to create a schema.
I keep getting the document does not have an _id error, besides the code below I did try to initialize it explicitly, but nothing works.
var UserSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
var User = mongoose.model('user', UserSchema);

http://mongoosejs.com/docs/guide.html#_id reads:
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor.
If you explicitly define _id type in the schema, it's your responsibility to set it:
User._id = mongoose.Types.ObjectId('000000000000000000000001');

_id is the primary key for document in a mongoDB. You don't have to specify the _id in your Schema. It will be added automatically once the document is created.
Here is the sample code:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
username: {
type: String
},
password: {
type: String
}
});
module.exports = mongoose.model('User', User);

I think you dont need to define the _id. Try without and see if it works.
Also if that is not the problem try this:
_id: { type: Mongoose.Schema.Types.ObjectId }

if you want to define _id in your schema explicity you should assign a value to "_id" for each insertation. you have two way to solve this problem :
1. remove "_id" from your schema and mongoose generate id automatically.
2. assign a value to _id :
var ObjectId = require('mongodb').ObjectID; // or var ObjectId = require('mongoose').Types.ObjectId; "but the first worked for me"
User._id = objectId('1111111111111111111');

simple remove the line from your code
_id: mongoose.Schema.ObjectId

Related

How to filter mongoose collection by Id node.js

Let's say I have a simple mongoose schema like this
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String;
age: String,
created: { type: Date, default: Date.now }
})
module.exports = mongoose.model('User', UserSchema);
I can easily find all User collections with User.find({}). But I want to find only specified collections by their _id.
For example I have 10 user collections, and want to find only users according their Id in this dynamic array
["5b66c0868278664f0d2f2fec","5b66c5a947eaed565b694efa"]
so I am required to use where or match?
did you try $in?
User.find({_id : {$in : ["5b66c0868278664f0d2f2fec","5b66c5a947eaed565b694efa"]})
The $in operator selects the documents where the value of a field
equals any value in the specified array. To specify an $in expression,
use the following prototype:
User.find({ _id: { $in: ["5b66577c2f05bf1eb07956e0" ,"5b66b1879526eb0444d047cb"] }})
.then(users =>{
console.log("user", users)
})
Pass user id in postman parameter, then assign it to a variable then pass it to the function which is written for db activities. Then modal.findone(id);

Nested Documents in Mongoose

I have two Mongoose schemas, User and Code. Each user can have many codes.
user.js:
var mongoose = require('mongoose');
var codeSchema = require('./code');
var userSchema = mongoose.Schema({
google: {
id: String,
token: String,
email: String,
name: String
},
codes: [codeSchema]
}, {collection : 'users'});
code.js:
var mongoose = require('mongoose');
var codeSchema = mongoose.Schema({
code: String,
name: String,
link: String
}, {collection: 'codes'});
module.exports = codeSchema;
My problem is, whenever I access a user's array of codes by user.codes, I get something like { _id: 56c4c82a37273dc2b756a0ce },{ _id: 56c4c82a37273dc2b756a0cd } rather than the JSON for a code.
What am I missing?
You're missing populate.
By default, Mongoose will only give you the _ids of any references made in a document. populate allows you to fill out nested documents.
userSchema.findOne({}).populate('codes');
More here
please check that you are inserting other values or not this can be a case . Please write how you are inserting in array . I have two other way check out
There are two way to do this
1-->either you save refrence id of codeschema and
2--> is you can insert whole codeschema in array
1. codes: {
type: mongooseSchema.ObjectId,
ref: 'codeSchema',
required: true
},
and when all data is in array 56c4c82a37273dc2b756a0ce,56c4c82a37273dc2b756a0cd
that can be done by this query
domain.User.update({_id:id}
,{$addToSet:{code:codeObjvalue}},
function(err,res){});
and then populate them by this
domain.users.find({},'code')
.populate('code','code color email').
exec(function(err,results){
callback(err, results);
});
2-- and second is to insert whole code schema in userschema
create a codeschema object and add in set like this
var codeobj={};
codeobj.code="xyz";
codeobj.email="xyz#gmail.com"
var codeobject = new domain.code(codeobj);
domain.User.update({_id:id},{$addToSet:{code:codeobject}},function(err,user1){
});
Woops, turns out I was using the wrong dataset, not adding the codes properly (facepalm). Thanks to everyone who answered!

Mongoose Saving _id's as Numbers

I would like to save an _id as a Number as seen in this documentation:
_id : Number,
Taken from here: http://mongoosejs.com/docs/populate.html
However, when using this code, I recieve no errors when saving data to the Model. If I remove this line it saves without failure as an ObjectID
My code:
var UserSchema = new Schema({
_id: Number
});
mongoose.model('User', UserSchema)
Mongoose automatically assigns an _id to every document you create being consistent with general MongoDB documents with an ObjectId by default. To change this behavior, just turn it off:
var UserSchema = new Schema({
_id: Number
},{ "_id": false });
mongoose.model('User', UserSchema)
So the _id generation is disabled by this option, and this could cause an error in a "top level" schema unless of course you define the field yourself. When you do then the type given is respected and used.
Without the option, the default is used and overrides any declaration you used in the schema. So this code now works as expected:
user = new User({ "_id": 1 });
user.save(function(err,doc) {
if (err) throw err; // but wont fail to cast type now
console.log( doc );
});

how to convert mongoose js model to object

i am working with node.js and mongoosejs framwork for mongodb. I am trying to convert a mongoose model to an object, I was able to do that, but am getting only fewer elements rather than getting all. Below code which I tried.
user.js
var schema = new Schema({
name:{ type:string },
title:{ type:string, default:"mr" }
});
module.exports = mongoose.model('Users', schema);
usermanager.js
var User = require(../user.js);
var user = new User();
console.log(user.toString());
//printed as {_id:2583457assda312, title:'mr'}
i am expecting name key in that object. i have also tryed toObject it also giveing me the same response.
ther is any posiblty to achive this?
Your usage is intended to be like this:
var user = new User({ name: "Fred" })
and you will get the values from what you have defined, so in this case:
//printed as {_id:2583457assda312, name: "Fred", title:'mr'}
Or you supply your title as here:
var user = new User({ name: "Wilma", title: "Ms" })
and again get your output
//printed as {_id:2583457assda312, name: "Wilma", title: "Ms"}
If what you are trying to do is inspect the schema there is a paths property on Mongoose schema objects
console.log( user.schema.paths )
And that should give you a definition of the various parts of the schema you defined.

I cannot upsert in Mongoose for Node.js

My schema is:
var VenueSchema = new Schema({
_id: Schema.Types.ObjectId
,rating : Number
})
And I am trying:
var v = new Venue()
v.name = venue.name
Venue.update({ id : Schema.Types.ObjectId(venue.id)}, v, {upsert: true})
But there is nothing in the DB. Where am I wrong?
You need to use _id instead of id and a plain JS object in the update call, and Mongoose will do the ObjectId casting for you. Try this instead:
Venue.update({ _id : venue.id}, {name: venue.name}, {upsert: true});
Note that name doesn't appear in your schema, which probably isn't what you want.

Resources