Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add field not in schema with mongoose

Tags:

I am trying to add a new field to a document, but this isn't working:

Creating my UserModel prototype:

model = require("../models/user") UserModel.prototype.findOneAndUpdate = function(query, params, cb) {     model.findOneAndUpdate(query, params, { returnNewDocument: true, new: true }, function(err, data) {         if (!err) {             cb(false, data);         } else {             cb(err, false);         }     }); }; 

Then calling it

userFunc = require("../../model_functions/user")  userFunc.findOneAndUpdate({     "email.value": userEmail }, {     $set: {"wat":"tf"} }, function (err, updatedUser) {     //This logs the updated user just fine, but the new field is missing         console.log(updatedUser);                   ... }); 

This successfully updates any field as long as it exists, but it won't add any new one.

like image 258
LuisEgan Avatar asked Jun 19 '18 18:06

LuisEgan


People also ask

Can I use Mongoose without schema?

To use Mongoose without defining a schema, we can define a field with the Mixed data type. const Any = new Schema({ any: Schema. Types. Mixed });

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

What does lean () do Mongoose?

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.


2 Answers

You can add and remove fields in schema using option { strict: false }

option: strict

The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.

var thingSchema = new Schema({..}, { strict: false }); 

And also you can do this in update query as well

Model.findOneAndUpdate(   query,  //filter   update, //data to update   { //options     returnNewDocument: true,     new: true,     strict: false   } ) 

You can check the documentations here

like image 123
Ashh Avatar answered Oct 19 '22 17:10

Ashh


You can add new fields in schema User using .add

require('mongoose').model('User').schema.add({fullName: String}); 

Thanks.-

like image 26
Alvaro Avatar answered Oct 19 '22 15:10

Alvaro