【问题标题】:query with mongoose用猫鼬查询
【发布时间】:2012-02-03 13:56:58
【问题描述】:

这是我的结构文件夹
-- express_example
|---- app.js
|---- 型号
|-------- 歌曲.js
|-------- 相册.js
|---- 和 expressjs 的另一个文件

song.js

var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;

var SongSchema = new Schema({
name: {type: String, default: 'songname'}
, link: {type: String, default: './data/train.mp3'}
, date: {type: Date, default: Date.now()}
, position: {type: Number, default: 0}
, weekOnChart: {type: Number, default: 0}
, listend: {type: Number, default: 0}
});

mongoose.model('Song', SongSchema);
module.exports = SongSchema;


album.js

var mongoose = require('mongoose')
, Schema = mongoose.Schema
, SongSchema = require('./songs')
, ObjectId = Schema.ObjectId;

var AlbumSchema = new Schema({
name: {type: String, default: 'songname'}
, thumbnail: {type:String, default: './public/images/album/unghoangphuc/U1.jpg'}
, date: {type: Date, default: Date.now()}
, songs: [SongSchema]
});

mongoose.model('Album', AlbumSchema);


我怎样才能将代码查询专辑按专辑ID放入文件album.js

【问题讨论】:

    标签: node.js mongodb mongoose express


    【解决方案1】:

    示例:

    var mongoose = require('mongoose')
      , Album = mongoose.model('Album'); 
    
    app.get('/posts/:id', function(req, res, next) {
      Album.findById(req.params.id, function(err, album) {
        // album is available here
      });      
    });
    

    请参阅 http://mongoosejs.com/docs/finding-documents.html 了解有关查找文档的更多信息。

    PS:这是我第三次回答你的问题了:)

    【讨论】:

    • :) 3 次我得到了你的回答,这对我非常有用。我可以将查询脚本像函数一样放在文件album.js 中,当我需要在某些单独的地方调用它时使用该函数
    • 对于简单的内置查询,没有必要这样做,它通常由控制器而不是模型来处理。对于复杂的查询,您可以在模型中添加新的方法,参见mongoosejs.com/docs/methods-statics.html
    • 好的.. 非常感谢:D...我很高兴你对我的帮助。我会尽力帮助像你一样帮助我的人。
    猜你喜欢
    • 2020-06-02
    • 2021-03-23
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 2014-10-22
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多