Nodejs Mongoose的model.find()查出来的为啥不是文档呢 求帮助

Nodejs Mongoose的model.find()查出来的为啥不是文档呢 求帮助

查询出来是一堆没用的东西呢,为啥不是文档呢:

//db.js var mongoose = require(‘mongoose’); mongoose.connect(‘mongodb://localhost/mybooks’); module.exports = mongoose;

//find.js var mongoose = require(’./db’); var Schema = mongoose.Schema; var booksSchema = new Schema({ name: String, author: String });

var bookModel = mongoose.model(‘ctbook’, booksSchema); console.log(bookModel.find());


{ _mongooseOptions: {}, mongooseCollection: { collection: null, opts: { bufferCommands: true, capped: false }, name: ‘ctbooks’, conn: { base: [Object], collections: [Object], models: {}, replica: false, hosts: null, host: ‘localhost’, port: 27017, user: undefined, pass: undefined, name: ‘mybooks’, options: [Object], otherDbs: [], _readyState: 2, _closeCalled: false, _hasOpened: false, _listening: false, _events: {}, db: [Object] }, queue: [], buffer: true }, model: { [Function: model] base: { connections: [Object], plugins: [], models: [Object], modelSchemas: [Object], options: [Object] }, modelName: ‘ctbook’, model: [Function: model], db: { base: [Object], collections: [Object], models: {}, replica: false, hosts: null, host: ‘localhost’, port: 27017, user: undefined, pass: undefined, name: ‘mybooks’, options: [Object], otherDbs: [], _readyState: 2, _closeCalled: false, _hasOpened: false, _listening: false, _events: {}, db: [Object] }, discriminators: undefined, schema: { paths: [Object], subpaths: {}, virtuals: [Object], nested: {}, inherits: {}, callQueue: [], _indexes: [], methods: {}, statics: {}, tree: [Object], _requiredpaths: undefined, discriminatorMapping: undefined, _indexedpaths: undefined, options: [Object], _events: {} }, options: undefined, collection: { collection: null, opts: [Object], name: ‘ctbooks’, conn: [Object], queue: [], buffer: true } }, op: ‘find’, options: {}, _conditions: {}, _fields: undefined, _update: undefined, _path: undefined, _distinct: undefined, _collection: { collection: { collection: null, opts: [Object], name: ‘ctbooks’, conn: [Object], queue: [], buffer: true } }, _castError: null }


7 回复

根据你提供的代码,问题出在 console.log(bookModel.find()); 这一行。model.find() 方法返回的是一个 Promise,而不是直接返回查询结果。你需要使用 .then()async/await 来处理这个 Promise。

示例代码

db.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mybooks', { useNewUrlParser: true, useUnifiedTopology: true });
module.exports = mongoose;

find.js

var mongoose = require('./db');
var Schema = mongoose.Schema;

// 定义书籍模型
var booksSchema = new Schema({
    name: String,
    author: String
});

var bookModel = mongoose.model('ctbook', booksSchema);

// 使用 async/await 处理 Promise
async function findBooks() {
    try {
        const books = await bookModel.find();
        console.log(books); // 打印查询结果
    } catch (error) {
        console.error(error);
    }
}

findBooks();

解释

  1. 连接 MongoDB

    • db.js 中,我们使用 mongoose.connect 方法连接到本地的 MongoDB 数据库 mybooks
    • 添加了 { useNewUrlParser: true, useUnifiedTopology: true } 参数来避免一些常见的警告信息。
  2. 定义模型

    • find.js 中,我们定义了一个书籍模型 booksSchema,它有两个字段:nameauthor
    • 使用 mongoose.model 方法创建一个模型实例 bookModel
  3. 查询数据

    • 使用 async/await 来处理异步操作,确保我们能够正确地获取到查询结果。
    • bookModel.find() 返回一个 Promise,我们需要等待这个 Promise 解析后才能获取到实际的数据。

通过这种方式,你可以正确地获取并打印查询结果,而不是打印一个 Promise 对象或一堆未解析的数据。


直接在用mongo能查到吗? 如果可以的话。那就是你mongoose用的有问题。 我是这样用的 <pre><code>var meetingSchema = new Schema({ id:Schema.Types.ObjectId, meetingRoomName: String, meetingId:String, meetingSubject:String, members: Schema.Types.Mixed, updated: { type: Date, default: Date.now }, startTime:{ type: Date, default: Date.now }, ownerCorpId:String, ownerName:String }); var meetingModel = mongoose.model(‘meetings’, meetingSchema); var query2 = meetingModel.find(conditions); query1.exec();</code></pre>

你这貌似打出来的是mongoose吧。

Model.find()查出来的就是文档 ,应该是哪里写错了吧 , 上代码瞧瞧

find查询出来的是mongoose的doc对象,支持update等操作,不是POJO,用doc.toObject()转换成POJO

bookModel.find({},[],{},function(err,docs){ console.log(docs); })

当你使用 model.find() 查询数据时,它并不会立即返回查询结果。相反,它会返回一个查询对象,你可以通过调用 .exec() 方法或者使用 .then() 来获取实际的数据文档。

以下是一个示例代码来说明如何正确处理 model.find() 的结果:

var mongoose = require('./db');
var Schema = mongoose.Schema;

// 定义书的模式
var booksSchema = new Schema({
    name: String,
    author: String
});

// 创建模型
var bookModel = mongoose.model('ctbook', booksSchema);

// 使用 .find().exec() 获取文档
bookModel.find().exec(function(err, books) {
    if (err) {
        console.error("查询出错:", err);
    } else {
        console.log("找到的书籍:", books);
    }
});

// 或者使用 .then() 处理 Promise
bookModel.find().then(books => {
    console.log("找到的书籍:", books);
}).catch(err => {
    console.error("查询出错:", err);
});

通过上述代码示例,你可以看到如何正确地从 model.find() 获取查询结果,并且可以打印出实际的文档。请注意,直接打印 bookModel.find() 是看不到实际数据的,因为这时查询操作还未执行。

回到顶部