使用mongoose将对象保存到MongoDB时出错。

问题描述 投票:0回答:2

所以我想用Mongoose node.js + express在MongoDB DBMS的apiregister上保存一个POST请求。

我的模式。

const mongoose = require('mongoose');

const obSchema = mongoose.Schema({

    ID: {
        type: Number,
        required: true,
        unique: true
    },
    description: { 
    type: String, 
    required: true
    },
    active: Boolean
});

module.exports = mongoose.model("OB", obSchema);

我的代码:

<express imports etc>
const OB = require('./models/ob.js');
app.post('/api/register', apiLimiter, async function (req, res){
  try  {
    OB.save(function (err) {
      if (err) return console.error(err);
      console.log("Saved successfully");
    });
  } catch (err) {
    res.status(500).send()
    console.log(err);
  }
});

我的错误:

TypeError: OB.save is not a function

node.js express mongoose mongoose-schema
2个回答
1
投票

TypeError.OB.save不是函数。OB.save不是一个函数

因为您操作的是原始 Mongoose 模型,而不是模型的实例。

而不是一个模型的实例。save 函数属于Mongoose模型的实例,要想在Mongo中保存文档必须先实例化一个模型。

const myOb = new OB({ ID: 1234, description: 'qwerty', active: true });

myOb.save((err) => {
  if (err) return console.error(err);
  console.log("Saved successfully");
});

Mongoose模型文档


0
投票

OB不是一个函数你可以试试这个。

const ob =new OB(data to be saved);

try{
await ob.save();
}
catch(e){
console.log(e)
}
© www.soinside.com 2019 - 2024. All rights reserved.