Giter VIP home page Giter VIP logo

mongoose-findorcreate's Introduction

Mongoose findOrCreate Plugin Build Status

Simple plugin for Mongoose which adds a findOrCreate method to models. This is useful for libraries like Passport which require it.

Installation

npm install mongoose-findorcreate

Usage

var findOrCreate = require('mongoose-findorcreate')
var ClickSchema = new Schema({ ... });
ClickSchema.plugin(findOrCreate);
var Click = mongoose.model('Click', ClickSchema);

The Click model now has a findOrCreate static method

Click.findOrCreate({ip: '127.0.0.1'}, function(err, click, created) {
  // created will be true here
  console.log('A new click from "%s" was inserted', click.ip);
  Click.findOrCreate({}, function(err, click, created) {
    // created will be false here
    console.log('Did not create a new click for "%s"', click.ip);
  })
});

You can also include properties that aren't used in the find call, but will be added to the object if it is created.

Click.create({ip: '127.0.0.1'}, {browser: 'Mozilla'}, function(err, val) {
  Click.findOrCreate({ip: '127.0.0.1'}, {browser: 'Chrome'}, function(err, click) {
    console.log('A click from "%s" using "%s" was found', click.ip, click.browser);
    // prints A click from "127.0.0.1" using "Mozilla" was found
  })
});

Promise Support

Choose your Promise library by setting Mongoose.Promise.

The returned Promise shall resolve to an object with keys doc and created on success. It shall be rejected with err on failure.

// Use environment-provided Promise (necessary to silence a Mongoose warning).
mongoose.Promise = Promise;
// To a findOrCreate().
Click.findOrCreate({ip: '127.0.0.2'}).then(function (result) {
  click = result.doc;
  console.log('A click from', click.ip, ' using ', click.browser, ' was ', click.created ? 'created' : 'found');
})

License

(The MIT License)

Copyright (c) 2012-2017 Nicholas Penree <[email protected]>

Based on supergoose: Copyright (c) 2012 Jamplify

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mongoose-findorcreate's People

Contributors

aanshsavla avatar ben-wd avatar ben305 avatar binki avatar chapel avatar drudge avatar fdezromero avatar joscha avatar massimiliano-scifo avatar mikxail avatar romanmt avatar tdharris avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

mongoose-findorcreate's Issues

TypeError: Cannot read properties of undefined (reading 'ES6')

`
const findOrCreate = require('mongoose-findorcreate');
const userSchema = new mongoose.Schema({
email: String,
password: String,
})

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = mongoose.model("User", userSchema)

passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function (accessToken, refreshToken, profile, cb) {
console.log(profile);

    User.findOrCreate({ googleId: profile.id }, function (err, user) {
        return cb(err, user);
    });
}

));`

Here is my code but I keep getting the error below.

TypeError: Cannot read properties of undefined (reading 'ES6')
at Function.findOrCreate (/home/fatih/Web Development/Secrets/node_modules/mongoose-findorcreate/index.js:11:37)
at Strategy._verify (/home/fatih/Web Development/Secrets/app.js:65:14)
at /home/fatih/Web Development/Secrets/node_modules/passport-oauth2/lib/strategy.js:205:24
at /home/fatih/Web Development/Secrets/node_modules/passport-google-oauth20/lib/strategy.js:122:5
at passBackControl (/home/fatih/Web Development/Secrets/node_modules/oauth/lib/oauth2.js:134:9)
at IncomingMessage. (/home/fatih/Web Development/Secrets/node_modules/oauth/lib/oauth2.js:157:7)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Mongoose findOrCreate not working

Mongoose findOrCreate not working after creating a folder 'Types'=> 'Mongoose': index.d.ts(Where i declared the findOrCreate module)

After all these, is not still working!. I don't know what could be wrong

Pushing to arrays through upsert

Hello,
I'm trying to find or upsert, but I have arrays in my Schema, and it apparently does not work to $push as in here

  User.findOrCreate({'social.facebook.id': profile.id},
	{
	  social: {
		facebook: {
		  id: profile.id,
		  first_name: profile.first_name,
		  last_name: profile.last_name,
		  access_token: {
			expires_at: new Date().getTime() + json.expires_in,
			token: accessToken
		  },
		  $push: {
			friends: profile.friends.data
		  }
		}
	  },
	  username: profile.email,
	  residence_location: profile.location,
	  gender: profile.gender,
	  email: profile.email,
	  birthday: profile.birthday,
	  $push: {
		photos: {
		  value: profile.picture
		}
	  }
	}, {
	  upsert: true
	}).then((user) => {
	winston.debug('Facebook user ', user.username)
	return done(null, user)
  }).catch((err) => {
	winston.debug('Facebook findOrCreate err: ', err)
	return done(null)
  })

Am I missing anything?

Why are the properties that contain the dollar sign eliminated?

Hello, i have this question , in a part of index.js have:

// If the value contain '$' remove the key value pair
        var keys = Object.keys(conditions);

        for (var z = 0; z < keys.length; z++) {
          var value = JSON.stringify(conditions[keys[z]]);
          if (value && value.indexOf('$') !== -1) {
            delete conditions[keys[z]];
          }
        }

I need to save
message = { text: "the price is $550"}
and I can't, have any solution?

Error with mongoose v5

When use this plugin with mongoose 5.0.0 I got an error

Promise is not a constructor

to solve this problem we need to remove .ES6 from promise implementation.

var Promise = self.base.Promise.ES6; -> var Promise = self.base.Promise;

at row 10 of "index.js" file.
Regards

How to import with type: "module" in Node.js

I'm using Node.js for the Backend of my app, and I want to implement this package.

I want to know how to write the proper import statement (using type: "module"). I think it is:

import findOrCreate from "mongoose-findorcreate";

But for some reason VSCode marks it as a warning. Can someone tell me how is the proper import statement?

why npm install mongoose-findorcreate failed

npm ERR! code ENOTFOUND
npm ERR! syscall getaddrinfo
npm ERR! errno ENOTFOUND
npm ERR! network request to https://registry.npmjs.org/mongoose-findorcreate failed, reason: getaddrinfo ENOTFOUND domain
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly. See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR! /home/tech/.npm/_logs/2022-09-25T17_28_35_196Z-debug-0.log

undefined ES6

TypeError: Cannot read properties of undefined (reading 'ES6')
at Function.findOrCreate (C:\Users\sagayaraj.s\desktop\desktop1\Secret - Starting Code\node_modules\mongoose-findorcreate\index.js:11:37)
please define ES6 and fix the code

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.