sql >> Base de Datos >  >> NoSQL >> MongoDB

Mongodb/mongoose insert no es una función

Verifique este ejemplo de código, debería funcionar como lo necesita.

No veo aquí ninguna parte que no comprenda.

Haga preguntas en los comentarios, puedo explicar si no entiendo.

var tokenSchema = mongoose.Schema({
  owner: { 
    type: 'String',
    required: true,
    index: {
      unique: true
    }
  }, 
  token: {
    type: ['String'],
    default: []
  }
});

var Token = module.exports = mongoose.model('tokens', tokenSchema);

//save token, if token document exist so push it in token array and save
module.exports.saveToken = function(owner_id, token, callback){
    Token
      .findOne({owner: owner_id})
      .exec(function(err, tokenDocument) {
        if(tokenDocument) {
          if(tokenDocument.token.indexOf(token) > -1) { // found that token already exist in document token array
            return callback(null, tokenDocument); // don't do anything and return to callback existing tokenDocument
          }

          tokenDocument.token.push(token);
          tokenDocument.save(callback);
          return; // don't go down, cuz we already have a token document
        }

        new Token({owner: owner_id, token: [token]}).save(callback); // create new token document with single token in token array
    });
}

//get all tokens by owner_id
module.exports.getAllTokens = function(owner_id, callback){
    Token
      .findOne({owner: owner_id})
      .exec(function(err, tokenDocument) {
        callback(err, tokenDocument.token);
      });
}