[英]Why the object returns undefined when output property?
At the server side with Node js, I am using Mongoose to query by the ID a document.在使用 Node js 的服务器端,我使用 Mongoose 通过 ID 查询文档。 I queried a document from mongodb to use the ID of that document to add some data to it.
我从 mongodb 中查询了一个文档,以使用该文档的 ID 向其中添加一些数据。 But when I want to use de ID of that document it is undefined.
但是当我想使用该文档的 de ID 时,它是未定义的。 Here is the code:
这是代码:
user.find({user: req.body.user}, function(err, doc) {
if(err) {
console.log(err);
} else {
console.log(doc + ' the document'); // Here returns the object with all properties
console.log(typeof doc + ' type of variable'); // Outputs Object
console.log(doc._id + ' the ID'); // Undefined
console.log(doc.user+ ' the user'); //Also undefined
user.findById(doc._id, function(err, user){
if(err) {
console.log(err);
} else {
console.log(user + ' <---');
// for (const iterator of req.body.list) {
// console.log(iterator);
// user.cases = iterator;
// user.save().then(person => {
// console.log('Added')
// })
// .catch(err => {
// console.log('Failed')
// });
// }
}
})
// console.log(doc + ' <--- Document');
}
});
})
Mongoose's Model.find()
always provides documents inside of a collection, even if there's only 1. This method is a shorthand for calling Query.find()
, which notes this more directly: Mongoose 的
Model.find()
总是在集合内提供文档,即使只有 1 个也是如此。此方法是调用Query.find()
的简写,它更直接地说明了这一点:
The result will be an array of documents.
结果将是一个文档数组。
With it, you'll have to access the desired document from the collection before accessing the _id
.有了它,您必须在访问
_id
之前从集合中访问所需的文档。
user.find({user: req.body.user}, function(err, docs /* note: plural */) {
if(err) {
console.log(err);
} else if (docs.length === 0) {
console.log('Not found');
} else {
console.log(docs[0]._id, 'the user');
let userDoc = docs[0];
console.log(userDoc._id, 'the user');
// ...
}
});
You can alternately use Model.findOne()
to get back only the first/single document that matches the query:您可以交替使用
Model.findOne()
只取回与查询匹配的第一个/单个文档:
user.findOne({user: req.body.user}, function(err, userDoc) {
if(err) {
console.log(err);
} else if (userDoc == null) {
console.log('Not found');
} else {
console.log(userDoc._id, 'the user');
// ...
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.