You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongo Shell无法识别Mongoose模型名ArtPiece,报错未定义求助

问题:Mongo Shell中无法通过Mongoose模型名访问数据

开发艺术藏品管理Web应用时,Mongoose与MongoDB连接正常,测试数据已成功存入数据库,但在Mongo Shell中尝试通过模型名ArtPiece访问数据时,出现「ReferenceError: modelName is not defined」错误,无法正常访问。

相关代码

models/artPiece.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const artPieceSchema = new Schema({
    title: String,
    artist: String,
    technique: String,
    year: Number,
    size_x: Number,
    size_y: Number,
    owner: String,
    holder: String,
    acquiration_date: Date, // if updated, have to notiy mongoose with 'doc.markModified('pathToYourDate')' -- check the docs if in doubt
    archival: Boolean,
    description: String,
},
{
    timestamps: true, 

}
);

const ArtPiece = mongoose.model('ArtPiece', artPieceSchema, 'artpieces');
module.exports = ArtPiece; 

app.js

const express = require('express');
const path = require('path');
const ejsMate = require ('ejs-mate');

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.use('/public', express.static('public'));

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/artCollection',
{ useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
    console.log('connection open!')
})
.catch(err => {
    console.log('oh no!')
    console.log(err)
});

const ArtPiece = require('./models/artPiece.js');


app.get('/makeArtPiece', async (req, res) => {
    const piece = new ArtPiece({
        title: 'Scream',
        artist: 'Munch' })
   
    await piece.save(); 
    res.send(piece)
    })

app.get('/collection', (req, res) => {
    res.render('collection')
});

app.listen(3000, () => {
    console.log('Serving on port 3000!')
});

测试对象已成功添加至数据库,但无法通过Mongo Shell使用模型名访问,求问题原因及解决方法。


解答

问题原因

Mongoose的模型名是Node.js应用层面的抽象,Mongo Shell并不识别Mongoose定义的模型名。Mongo Shell直接操作MongoDB的原生集合,和Mongoose的模型没有直接关联,所以在Shell里直接输入ArtPiece会提示未定义。

你的代码中已经显式指定集合名为artpieces(mongoose.model('ArtPiece', artPieceSchema, 'artpieces')的第三个参数),数据实际存储在artCollection数据库的artpieces集合中。

解决方法

在Mongo Shell中直接操作对应的原生集合即可:

  1. 进入目标数据库:
use artCollection
  1. 执行数据操作示例:
db.artpieces.find() # 查询所有文档
db.artpieces.findOne({title: 'Scream'}) # 查询单个匹配文档

如果需要在Shell中模拟Mongoose模型的操作方式,需临时重新定义模型(但实际开发中没必要,直接操作集合更高效):

# 在Mongo Shell中临时定义Schema和模型
const artPieceSchema = new mongoose.Schema({
    title: String,
    artist: String,
    // 其他字段结构与你的Schema保持一致
});
const ArtPiece = mongoose.model('ArtPiece', artPieceSchema, 'artpieces');
ArtPiece.find().then(console.log);

注意:这种方式每次启动Shell都要重新定义,且需确保Shell已加载mongoose环境。

内容的提问来源于stack exchange,提问作者Mer Danii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:40:25