How to prevent Mongoose findOneAndUpdate to add ObjectId automatically - node.js

I have a collection with the following document
{_id:'12345',account:{ba:0,br:0,ac:0}, scores:{a:0,b:0}}
I have a resolver and after running it
const input = {account:{ba:1,br:2,ac:3}, scores:{a:1,b:1}}
const profileId='12345'
const res = await modelProfile.findOneAndUpdate({ _id: profileId }, input);
it finds the document and properly changes it but it is adding also _id to each object there :
{_id:'12345',account:{_id:'46456',ba:1,br:2,ac:3}, scores:{_id:'4645677', a:1,b:1}}
How can I prevent mongoose from automatically adding _id to the SUBDOCUMENT objects of the document that they don't have ObjectId already. (as you saw, the document has ObjectId but objects inside as subdocuments does not have it)

I found the solution, I should change schema
var subSchema = mongoose.Schema({
// your subschema content
}, { _id : false });

Related

How to set a field value with same document id in mongoose

I want to create a schema on mongoose where a field value is the same as document id.
Desired output:
{
"_id": "61c75bf3b151c6c6854c83db",
"password":"some password",
"name":"some name",
"linkId": "61c75bf3b151c6c6854c83db"
}
Here document id and linkId is same. How can I do that when creating a new document? It maybe redundant but is it possible?
You can use pre-hook middleware for the save method, when you insert any document it will clone the _id field in to linkId field,
// SCHEMA
const SchemaObj = new mongoose.Schema(
// your schema...
);
// PRE MIDDLEWARE
SchemaObj.pre('save', function (next) {
this.linkId = this._id;
next();
});

document must have an _id before saving mongoose error

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

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 );
});

Mongoose findByIdAndUpdate removes not updated properties

I have the following Mongoose model:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
facebook: {
name: String,
email: String,
customerId: String
}
});
var User = mongoose.model('User', userSchema);
When I update a part of this document using findByIdAndUpdate
User.findByIdAndUpdate(id, {
$set: {
facebook: {
name: name
}
}
});
name gets updated, while email and customerId get removed (unset?).
I didn't find this documented.
Is there a way to update only specific document properties with findByIdAndUpdate?
FindByIdAndUpdate is actually Issues a mongodb findAndModify update command by a documents id.
The point is you are setting an object to overwrite the old object. if you want to update a field you need to modify your update object.
User.findByIdAndUpdate(id, {
$set: {
'facebook.name':name
}
});
This will only update the name field keeping rest of the field of the old object.

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