Mongodb/mongoose 插入不是一个函数 [英] Mongodb/mongoose insert is not a function

查看:26
本文介绍了Mongodb/mongoose 插入不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的插入不工作,我得到错误的错误:

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

Token.insert 不是函数

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

推荐答案

检查此代码示例,它应该可以正常工作.

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

这篇关于Mongodb/mongoose 插入不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆