Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - Mongodb/mongoose insert is not a function

My insert is not working, I got error of Error :

Token.insert is not a function

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

//error
module.exports.saveToken = function(owner_id, token, callback){
    console.log(owner_id,token);
    Token.insert({"owner":owner_id,"token":token},callback);
}
//working
module.exports.getAllTokens = function(owner_id, callback){
    Token.find({"owner":owner_id},callback);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check this code example, it should work as You need.

I don's see here any non-understanding part.

Ask questions in comments, I can explain if don't understand.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...