javascript 在mongoose中使用两个数据库

q3qa4bjr  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(104)

我想在mongoose中使用另一个db,所以我有这个:

const mongoose = require('mongoose');
const connectionOptions = { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false };
const conn = mongoose.createConnection("mongodb://localhost/db_en", connectionOptions);

const Schema = mongoose.Schema;

const priceSchema = new Schema({

    fixed: {
        1: { type: Number, default: 199 }, 
        3: { type: Number, default: 499 }, 
        6: { type: Number, default: 729 },
        12: { type: Number, default: 999 }
    }
});

conn.model('Price', priceSchema);

然后,我想在新数据库中向Price模型添加数据:

const ggg = new conn.Price();

 await ggg.save();

但它每次都返回这个错误:
TypeError:conn.Price不是构造函数

3pvhb19x

3pvhb19x1#

您需要将模型指定给某个对象才能访问它。下面是一个例子:

const priceSchema = new Schema({

    fixed: {
        1: { type: Number, default: 199 }, 
        3: { type: Number, default: 499 }, 
        6: { type: Number, default: 729 },
        12: { type: Number, default: 999 }
    }
});
var priceModel = mongoose.model('Price', priceSchema);
var price = new priceModel();

price.save(function (err, comment) {
    if (err) console.log(err);
    else console.log('fallowing price was saved:', price);
});

相关问题